Php 将两个查询的结果连接在一起

Php 将两个查询的结果连接在一起,php,mysql,sql,join,Php,Mysql,Sql,Join,我正在尝试将两个或多个查询的结果合并在一起。我已经查看了union和join,但似乎没有得到我想要的结果。我希望结果是id\u competitor,total\u products,discarted\u products(列)。非常感谢在这方面的任何帮助 编辑:添加了查询结果的图片。。我想通过'id_'竞争对手将这些表连接在一起。 这些值不应为null 产品总数: 讨论: 问题1: SELECT id_competitor, COUNT(competitor_product_variatio

我正在尝试将两个或多个查询的结果合并在一起。我已经查看了
union
join
,但似乎没有得到我想要的结果。我希望结果是
id\u competitor
total\u products
discarted\u products
(列)。非常感谢在这方面的任何帮助

编辑:添加了查询结果的图片。。我想通过'id_'竞争对手将这些表连接在一起。 这些值不应为null

产品总数: 讨论:

问题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

使用条件聚合

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\u产品
,请在
competitor\u产品
表中使用
left join
。我想所有的产品都在这张表里

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

编辑您的问题,并提供样本数据和所需结果。我将使用案例和原始
竞争对手产品变体的
COUNT
。另外,在MySQL中,当
SUM(is_related=1)
也可以使用时,您可以跳过大小写。@lad2025。而且
SUM(is_related=1)
更简洁,我同意。@vkp从结果查询构造正确但其值不正确的意义上讲,这是有效的,您为什么这么认为?如果您发布一些示例数据和预期结果,这会有所帮助。@vkp我确实发布了lol。我发布了查询中的数据。。我想要结果加入