【问题标题】:codeigniter select min and max product price from multy tablescodeigniter 从多个表中选择最小和最大产品价格
【发布时间】:2021-01-09 09:36:58
【问题描述】:

我需要从产品、价格中选择所有 (*) 行。但我需要从价格中选择 MIN 和 MAX 价格。我已经阅读了如何执行此操作,但是如何在 INNER JOIN 中执行此操作

这是我的 build_query() 函数:

 //build sql query string
public function build_query($type = "active")
{
    $select = "products.*,

        (SELECT CONCAT(price) FROM prices WHERE products.id = prices.product_id ORDER BY created_at DESC LIMIT 1) AS price;}

这是我的 products_maxmin_price() 函数:

public function get_shops_products_maxmin_price($parent_id)
{
    $this->build_query();
    $this->db->select('MAX(price) as p_max, MIN(price)  p_min ');
    $this->db->where('products.parent_id', clean_number($parent_id));
    return $this->db->get('products')->result();
}

这是我的观点:

<?php foreach ($shops_products_maxmin_price as $item): ?>
                         <?php echo $item->p_min; ?>
                        <?php endforeach; endif; ?>

<?php foreach ($shops_products_maxmin_price as $item): ?>
                         <?php echo $item->p_max; ?>
                        <?php endforeach; endif; ?>

【问题讨论】:

  • 为什么将价格存储在单独的表格中?
  • 因为我们需要价格历史记录,一个产品在同一日期有一些价格
  • 如果是我,我会从原始查询开始

标签: mysql codeigniter


【解决方案1】:

试试下面这个查询:

SELECT MIN(`prices`.`price`) as `p_min`,
       MAX(`prices`.`price`) as `p_max`,
       `products`.*
FROM `prices`
JOIN `products`
ON `prices`.`product_id` = `products`.`id`
WHERE `products`.`parent_id` = `<PARENT_ID>`
GROUP BY `prices`.`product_id`;

我修改了这个问题的答案:MIN/MAX price for each product (query)

更新: 将查询转换为 Codeigniter 查询生成器,并将您的 2 函数合并为 1:

public function get_shops_products_maxmin_price($parent_id)
{
    $this->db->select_min('prices.price','p_min');
    $this->db->select_max('prices.price','p_max');
    $this->db->select('products.*');
    $this->db->join('products', 'prices.product_id = products.id');
    $this->db->where('products.parent_id', clean_number($parent_id));
    $this->db->order_by('prices.created_at','DESC');
    $this->db->group_by('prices.product_id');
    return $this->db->get('products')->result();
}

【讨论】:

  • 错误:消息:未定义的属性:stdClass::$p_min
  • 这只是一个 SQL 查询!不要尝试用 PHP 运行!我试图帮助您找到针对您的问题的正确查询。您需要将此查询转换为您的代码,因为我(我们)不知道您的环境详细信息
  • 我是初学者,无法在codeigniter中使用您的查询,如果可以请在我的函数中申请
  • 那你必须先学习基础知识,然后才能处理更严肃的项目
  • 错误号:1064 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以了解在 'JOIN products ON prices.product_id = products.id WHERE products.par' at line 2 SELECT MIN(prices.附近使用的正确语法price) AS p_min, MAX(prices.price) AS p_max, products.* JOIN products` ON prices.product_id = products.id WHERE products.parent_id = 1 组由prices.product_id 订购prices.created_at DESC
猜你喜欢
  • 2013-01-14
  • 2018-04-26
  • 2020-10-29
  • 2015-11-05
  • 2017-12-05
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 2015-04-22
相关资源
最近更新 更多