尝试使用左连接和分组进行查询并在 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上处理此问题的正确方法是什么?提前致谢!
Im trying to make some queries, first, I do this one (and works):
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;
But when I do this one, it gaves me an empty set, the difference is that it has a "HAVING" at the end of the query over a field that may be: 0, 1 or NULL (because of the LEFT JOIN, I have no groups linked to the table 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;
So, I tried the following ways but no one works:
-- HAVING G.active=1
-- HAVING G.active=1 OR G.active=NULL
-- HAVING G.active0
What is the right way to handle this on MySQL? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将值与
NULL
进行比较的正确方法是IS NULL
。因此,您需要添加HAVING G.active IS NULL OR G.active=1
。您的代码G.active=NULL
始终为NULL
(false):The proper way to compare value with
NULL
isIS NULL
. So you need to addHAVING G.active IS NULL OR G.active=1
. Your codeG.active=NULL
is alwaysNULL
(false):为什么不在“Group”ON 条件上添加 HAVING 条件?
Why you don't add the HAVING condition on the "Group" ON condition?