Sql查询2个表的并集

时间:2014-03-08 18:02:24

标签: mysql

我遇到了一个问题。我有两个表,两个表都有一个共同的列,但两者中的数据可能不同:

标签1

+---------+------------+
|   Sub   | student_id |
+---------+------------+
| Math    | 0033       |
| Science | 0034       |
| Geom    | 0035       |
| Math    | 0034       |
+---------+------------+

标签2

+---------+----------+
|   Sub   | class_id |
+---------+----------+
| Science | 001      |
| Geom    | 002      |
| Geom    | 001      |
| Civics  | 004      |
+---------+----------+

现在我需要以下列方式获得结果:

+---------+----------------+--------------+
|   Sub   | Student(count) | Class(count) |
+---------+----------------+--------------+
| Math    | 2              | 0            |
| Science | 1              | 1            |
| Geom    | 1              | 2            |
| Civics  | 0              | 1            |
+---------+----------------+--------------+

我想我必须使用union,我可以在两个不同的查询中获得结果,但我无法像上面那样显示最终表格。

这就是我所拥有的:

select sub,count(*)as student_id from tab1
group by sub
union
select sub,count(*)as class_id from tab2
group by sub

但是我得到2个cols而不是3个。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

尝试这个

SELECT AllSubs.Sub as Sub,
       COUNT(DISTINCT tab1.Student_Id) as "Student(Count)",
       COUNT(DISTINCT tab2.Class_Id) as "Class(Count)"
FROM
(SELECT DISTINCT Sub FROM tab1
UNION
SELECT DISTINCT Sub FROM tab2)AllSubs
LEFT JOIN tab1 ON tab1.Sub = AllSubs.Sub
LEFT JOIN tab2 ON tab2.Sub = AllSubs.Sub
GROUP BY AllSubs.Sub

sqlFiddle

查询从tab1和tab2中选择所有不同的主题,然后与tab1和tab2保持联接,然后计算不同的studdent_id并按主题统计不同的class_id分组。

已更新

SELECT AllSubs.Sub as Sub,
       COUNT(DISTINCT tab1.Student_Id) as "Student(Count)",
       COUNT(DISTINCT tab2.Class_Id) as "Class(Count)",
       COUNT(DISTINCT tab1.Student_Id) - COUNT(DISTINCT tab2.Class_Id) as difference
FROM
(SELECT DISTINCT Sub FROM tab1
UNION
SELECT DISTINCT Sub FROM tab2)AllSubs
LEFT JOIN tab1 ON tab1.Sub = AllSubs.Sub
LEFT JOIN tab2 ON tab2.Sub = AllSubs.Sub
GROUP BY AllSubs.Sub
ORDER BY difference DESC

sqlFiddle

如果您只想要第一行,只需将LIMIT 1添加到查询结尾。