我正在尝试编写一个查询以将多个表连同count和group by联接在一起,但是失败了。 (初级)
有两个表。 two tables(t1, t2)
查询结果预期: expected result
我可以成功地单独完成它们,但不能将它们加入一个表中。 查询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;
请帮助,谢谢。
答案 0 :(得分:2)
理想情况下,应该有一些主表,其中包含要显示在报告中的所有名称。为了便于说明,我们可以为此使用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中也是如此),但这仅在两个表共同包含您希望显示的所有名称的情况下才能满足您的要求。如果没有,那就行不通了。