我有2张桌子。
First table - products
products_id | quantity
1001,1
1002,2
1003,5
1004,4
Second table - products_catalog
products_catalog_id | products_id | partner_channel |active_status
1,1001,amazon,0
2,1001,ebay,0
3,1001,zalando,1
4,1002,amazon,1
5,1002,ebay,0
6,1003,amazon,1
7,1003,ebay,1
8,1003,zalando,1
9,1004,amazon,0
10,1004,ebay,0
11,1004,zalando,0
如果此产品在任何合作伙伴渠道中无效,我希望产品ID的结果符合条件(active_status = 0) 我正在使用WHERE过滤器:
SELECT p.products_id, pc.partner_channel, pc.active_status
FROM products p
LEFT JOIN products_catalog pc ON pc.products_id=p.products_id
WHERE pc.active_status='0'
GROUP BY p.products_id ORDER BY p.products_id;
WHERE active_status = 0,但结果如下:
products_id | partner_channel | active_status
1001,amazon,0
1002,ebay,0
1004,amazon,0
我想要这样的结果表产品:
products_id | partner_channel | active_status
1004,amazon,0
因为在所有partner_channel中只有此产品ID(1004)具有active_status = 0.。
我想我错过了WHERE过滤器中的某些内容,但对此没有任何线索。也许我应该在LEFT JOIN到products_catalog时使用子查询?
任何帮助将不胜感激。
感谢。
答案 0 :(得分:2)
使用具有功能。
coordinatesX[1]
答案 1 :(得分:1)
您必须在HAVING
子句中放置一个条件,如下所示:
SELECT products_id
FROM products_catalog
GROUP BY products_id
HAVING SUM(active_status <> 0) = 0;
此查询会返回与{strong>所有 products_id
相关的active_status = 0
partner_channel
个值。
然后,您可以使用上述查询作为派生表连接回原始表,以获取其余字段:
SELECT p.*, pc.*
FROM products p
JOIN products_catalog pc ON pc.products_id=p.products_id
JOIN (
SELECT products_id
FROM products_catalog
GROUP BY products_id
HAVING SUM(active_status <> 0) = 0
) AS g ON g.products_id = p.products_id
ORDER BY p.products_id
答案 2 :(得分:0)
试用此代码
SELECT p.products_id, pc.partner_channel, pc.active_status
FROM products p
LEFT JOIN products_catalog pc ON pc.products_id=p.products_id
WHERE pc.active_status='0'
GROUP BY p.products_id ORDER BY p.products_id DESC;