[英]join SQL query problem
我有以下查詢,該查詢返回產品和找到的最低售價以及該售價的數量。 一切工作正常,直到我想要獲得在product_price表中沒有任何價格的產品。 我怎樣才能讓它返回產品價格和空值的空值?
SELECT p.*, MIN(pp.sellPrice) as sellPrice, pp.quantity FROM `product` as p
LEFT JOIN `product_price_group` as ppg ON ppg.productId = p.`id`
LEFT JOIN `product_price` as pp ON pp.priceGroupId = ppg.`id`
WHERE p.`id` = 1 AND p.`active` = 1
具有可用價格的產品的輸出:
+----+--------------+--------+--------------+--------------+-----------+----------+
| id | name | active | sortSequence | creationDate | sellPrice | quantity |
+----+--------------+--------+--------------+--------------+-----------+----------+
| 1 | product_id_1 | 1 | 1 | 1287481220 | 22.00 | 10 |
+----+--------------+--------+--------------+--------------+-----------+----------+
沒有定價的產品的輸出
+----+------+--------+--------------+--------------+-----------+----------+
| id | name | active | sortSequence | creationDate | sellPrice | quantity |
+----+------+--------+--------------+--------------+-----------+----------+
| NULL | NULL | NULL | NULL | NULL | NULL | NULL |
+----+------+--------+--------------+--------------+-----------+----------+
所需的輸出:
+----+--------------+--------+--------------+--------------+-----------+----------+
| id | name | active | sortSequence | creationDate | sellPrice | quantity |
+----+--------------+--------+--------------+--------------+-----------+----------+
| 2 | product_id_2 | 1 | 1 | 1287481220 | NULL | NULL |
+----+--------------+--------+--------------+--------------+-----------+----------+
更新似乎我在選擇不存在的產品! 很蠢
對product_price表使用LEFT OUTER JOIN怎么樣?
SELECT p.*, MIN(pp.sellPrice) as sellPrice, pp.quantity FROM `product` as p
LEFT JOIN `product_price_group` as ppg ON ppg.productId = p.`id`
LEFT OUTER JOIN `product_price` as pp ON pp.priceGroupId = ppg.`id`
WHERE p.`id` = 1 AND p.`active` = 1
這是你想要的嗎?
更新:修訂-像其他人說的那樣, LEFT JOIN = LEFT (OUTER) JOIN
因此在這種情況下它對您沒有幫助...
我可能不正確,但是我對LEFT JOIN的理解一直是SQL語句中編寫的相等性測試中的表引用……此外,我如何編寫查詢……從表開始期望FIRST(左),第二次連接到OTHER(右)表...還要保持該關系的各自連接條件...
select from x left join y where x.fld = y.fld
instead of
select from x left join y where y.fld = x.fld
因此,我將按以下方式調整您的查詢
SELECT
p.*,
MIN(pp.sellPrice) as sellPrice,
pp.quantity
FROM
product as p
LEFT JOIN product_price_group as ppg
ON p.id = ppg.productId
LEFT JOIN product_price as pp
ON ppg.id = pp.priceGroupId
WHERE
p.id = 1
AND p.active = 1
另外,您可以使用IFNULL(field,0)包裝min()和數量,以防止顯示NULL,而實際為零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.