将两个查询的结果一起加入

时间:2015-12-29 14:42:13

标签: php mysql sql join

我试图将两个或多个查询的结果连接在一起。我看过unionjoin,但似乎无法获得我之后的结果。我希望结果为id_competitortotal_productsdiscarted_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

1 个答案:

答案 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