我有以下查询返回产品和最低卖价与销售价格的数量。一切都运作良好,直到我想得到product_price表中没有任何价格的产品。如何退回产品数据和NULLS以获取售价和数量?
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 |
+----+--------------+--------+--------------+--------------+-----------+----------+
更新 看来我正在选择不存在的产品!非常愚蠢。
答案 0 :(得分:0)
如何在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
所以在这种情况下它不会帮助你......
答案 1 :(得分:0)
我可能不正确,但我对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(字段,0)包装min()和数量,以防止显示NULLS,但实际上是零值。