簡體   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