繁体   English   中英

选择具有多个联接和条件的列,其中null为null

[英]select with multiple join and conditions where column null codeigniter

我正在寻找从数据库中获得项目,其中项目有选项,而有些则没有。

我获取数据的模型是:{这仅返回product.id位于options和option_values中的产品}

$category_id = 2;
$this->db->select('category_products.*, products.*, option_values.price as prodPrice, option_values.special_price, LEAST(IFNULL(NULLIF(option_values.special_price, 0), option_values.price), option_values.price) as sort_price', false)
         ->from('category_products')
         ->join('products', 'category_products.product_id=products.id')
         ->join('options', 'options.product_id=attributes.product_id')
         ->join('option_values', 'option_values.option_id=options.id')
         ->where('category_products.category_id', $category_id)
         ->where('option_values.inventory >', '0');
         ->where('products.quantity >', '0');
$this->db->group_by('products.id');

$result = $this->db->get()->result();
return $result;

但是我还需要获取没有options和options_values的项目。

category_products表:

product_id | category_id | sequence
74 | 2 | 0
75 | 2 | 0

产品表:

id | code | name | type | price | saleprice | quantity
74 | 12345_ | Product with options | 1 | 0 | NULL | 1
75 | 12346_ | Product without options | 2 | 199 | NULL | 1

选项表:

id | product_id | sequence | name | type | required
74 | 74 | 1 | Size | radiolist | 1

option_values表:

id | option_id | name | value | price | special_price | weight | inventory | sequence | limit
777 | 74 | 8K | 12345 | 199.00 | 159.00 | 1.00 | 0 | 17 | NUL

使用上面我写的模型,我只能获得product_id 74,而我的问题是我该如何调整查询以获取product_id 75?

任何帮助表示赞赏。

尝试更改联接以包括LEFT JOIN 我没有建立数据库,所以无法测试,但是我可以尝试以下操作:

注意 :在join()函数中添加了left参数。

$category_id = 2;
            $this->db->select('category_products.*, products.*, option_values.price as prodPrice, option_values.special_price, LEAST(IFNULL(NULLIF(option_values.special_price, 0), option_values.price), option_values.price) as sort_price', false)
                    ->from('category_products')
                    ->join('products', 'category_products.product_id=products.id', 'left')
                    ->join('options', 'options.product_id=attributes.product_id', 'left')
                    ->join('option_values', 'option_values.option_id=options.id', 'left')
                    ->where('category_products.category_id', $category_id)
                    ->where('option_values.inventory >', '0');
                    ->where('products.quantity >', '0');
            $this->db->group_by('products.id');

            $result = $this->db->get()->result();

            return $result;

您可能需要将联接修改为LEFTRIGHT联接才能获得所需的结果。 一分钟后,我可能会尝试对其进行仿真。

这是一篇有关理解MySQL连接的好文章 当我不得不编写复杂的查询时,我会不时提及它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM