我试图将两个或多个查询的结果连接在一起。我看过union
和join
,但似乎无法获得我之后的结果。我希望结果为id_competitor
,total_products
,discarted_products
(作为列)。任何有关这方面的帮助都非常感谢
编辑:添加查询结果的图片,因为它们代表..我想通过`id_competitor一起加入表。 值不应为null
总生产:total products query discarted:discarted products query
查询1:
SELECT id_competitor, COUNT(competitor_product_variation.id_product) AS total_products
FROM competitor_product
JOIN competitor_product_variation USING(id_product)
WHERE is_related = 1
GROUP BY id_competitor
查询2:
SELECT id_competitor, COUNT(competitor_product_variation.id_product) AS discarted_products
FROM competitor_product
JOIN competitor_product_variation USING(id_product)
WHERE is_related = 3
GROUP BY id_competitor
答案 0 :(得分:2)
使用条件聚合。
SELECT id_competitor
,sum(case when is_related = 1 then 1 else 0 end) AS total_products
,sum(case when is_related = 3 then 1 else 0 end) AS discarted_products
FROM competitor_product
JOIN competitor_product_variation USING(id_product)
GROUP BY id_competitor
修改:如果要返回所有id_product
,请在left join
表上使用competitor_product
。我假设所有产品都在这张表中。
SELECT cp.id_competitor
,sum(case when is_related = 1 then 1 else 0 end) AS total_products
,coalesce(sum(case when is_related = 3 then 1 else 0 end), 0) AS discarted_products
FROM competitor_product cp
LEFT JOIN competitor_product_variation cpv on cp.id_product = cpv.id_product
GROUP BY cp.id_competitor