sql连接多个重复条目的表,count()按组

c9x0cxw0  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(282)

我正在尝试编写一个查询,将多个表与count和group by连接在一起,但失败了(入门篇)
有两张table。两张table(t1、t2)
查询结果应为:应为结果
我可以成功地分别完成它们,但不能将它们合并到一个表中。查询1:

select name, count(name) from t1
group by name;

问题2:

select name, count(name) from t2
group by name;

问题3:

select name, count(total.name) as totalNum
from (select name from t1 union all select name from t2) as total
group by name;

查询4(失败):

select total.name, (select count(name) from t1) as t1count, (select count(name) from t2) as t2count
from (select name from t1 union select name from t2) as total
group by total.name;

请帮忙,谢谢。

slhcrj9b

slhcrj9b1#

理想情况下,应该有一个主表,其中包含要在报表中显示的所有名称。为了便于说明,我们可以为此使用cte/子查询。我们可以将这个子查询连接到在两个表中分别进行计数的子查询。

SELECT
    n.Name,
    COALESCE(t1.t1count, 0) AS t1count,
    COALESCE(t2.t2count, 0) AS t2count,
    COALESCE(t1.t1count, 0) + COALESCE(t2.t2count, 0) AS totalNum
FROM
(
    SELECT 'n1' AS Name UNION ALL
    SELECT 'n2' UNION ALL
    SELECT 'n3' UNION ALL
    SELECT 'n4' UNION ALL
    SELECT 'n5'
) n
LEFT JOIN
(
    SELECT Name, COUNT(*) AS t1count
    FROM t1
    GROUP BY Name
) t1
    ON n.Name = t1.Name
LEFT JOIN
(
    SELECT Name, COUNT(*) AS t2count
    FROM t2
    GROUP BY Name
) t2
    ON n.Name = t2.Name;

演示

请注意,您可以尝试使用完整的外部连接方法(即使在mysql中),但只有当两个表都包含您希望显示的所有名称时,这才能满足您的要求。如果不行,那就不行了。

相关问题