我有一个语句,它计算有多少记录attr3 = 1
。
SELECT 'Dept' AS table_name, COUNT(*)
FROM ((select attr3 from table1) union all
(select attr3 from table2)
) t
WHERE attr3 = '1';
现在我需要另一个语句来执行相同的操作,但要计算有多少记录
attr3 = 2
。SELECT 'Dept' AS table_name, COUNT(*)
FROM ((select attr3 from table1) union all
(select attr3 from table2)
) t2
WHERE attr3 = '2';
理想情况下,数据将以这种格式显示
Dept count(*)
attr3 = 1 4
attr3 = 2 6
如果我单独做这些语句,这个方法就行了,我只想把它们连接在一起。有人能帮忙吗?
最佳答案
简单的GROUP BY
和WHERE attr3 in()
就足够了。
SELECT Z.attr3 as Dept, count(*) as cnt
FROM (SELECT attr3 FROM table1
UNION ALL
SELECT attr3 FROM table2) Z
WHERE attr3 in ('1','2')
GROUP BY Z.attr3
因为attr3定义了要计算的组,所以只需按它分组,并通过where子句将结果限制在联合后的1,2。
关于mysql - 如何在两个语句上使用联接?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41186418/