[英]Problems while trying to make a query using left join and group by with having over a field of the left table on MySQL
我正在尝试进行一些查询,首先,我做了一个(并且可行):
SELECT RP.id, RP.product_name, RP.price, RP.retailer_id, RP.product_id,
count(G.id) AS duration, G.active, RP.retprod_id, P.pr_id AS video
FROM retailer_products AS RP
LEFT JOIN groups G ON RP.id=G.retailer_product_id
INNER JOIN products P ON P.id=RP.product_id
WHERE (RP.product_id IN (1))
GROUP BY RP.id;
但是当我执行此操作时,它给了我一个空集,不同之处在于它在查询结束时在一个字段上可能有一个“ HAVING”,该字段可能是:0、1或NULL(由于使用了LEFT JOIN,我没有与表retailer_product链接的组)
SELECT RP.id, RP.product_name, RP.price, RP.retailer_id, RP.product_id,
count(G.id) AS duration, G.active, RP.retprod_id, P.pr_id AS video
FROM retailer_products AS RP
LEFT JOIN groups G ON RP.id=G.retailer_product_id
INNER JOIN products P ON P.id=RP.product_id
WHERE (RP.product_id IN (1))
GROUP BY RP.id HAVING G.active=1;
因此,我尝试了以下方法,但没有一个起作用:
-- HAVING G.active=1
-- HAVING G.active=1 OR G.active=NULL
-- HAVING G.active0
在MySQL上处理此问题的正确方法是什么? 提前致谢!
将值与NULL
比较的正确方法是IS NULL
。 因此,您需要添加HAVING G.active IS NULL OR G.active=1
。 您的代码G.active=NULL
始终为NULL
(假):
1 = NULL // NULL - false in conditions
NULL = NULL // NULL - false in conditions
NULL IS NULL // TRUE
为什么不在“组”打开条件上添加HAVING条件?
SELECT RP.id, RP.product_name, RP.price, RP.retailer_id, RP.product_id,
count(G.id) AS duration, G.active, RP.retprod_id, P.pr_id AS video
FROM retailer_products AS RP
LEFT JOIN groups G ON RP.id=G.retailer_product_id AND G.active=1
INNER JOIN products P ON P.id=RP.product_id
WHERE (RP.product_id IN (1))
GROUP BY RP.id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.