所以这些表格是这样的:
表1:
facilities emails
Fac 1 fac1@email.com
Fac 2 fac2@email.com
Fac 1 RE fac1@email.com
表2:
facilities emails
fac1 fac1@email.com
fac2 fac3@email.com
现在,在这两张桌子上,我试图弄清楚有多少设施在使用每个地址电子邮件。我有两个SQL查询就是这样:
SELECT ce.email, count(*)
AS TOTAL_FACILITIES
FROM table1
AS ce
GROUP BY ce.email
ORDER BY TOTAL_FACILITIES DESC
SELECT ca.emails, count(*)
AS TOTAL_FACILITIES
FROM table2
AS ca
GROUP BY ca.emails
ORDER BY TOTAL_FACILITIES DESC
这为我提供了每张桌子的不同电子邮件以及有多少设施使用它们。我现在尝试使用联接将其组合成一个单独的调用,但我似乎无法弄清楚如何使计数工作。
有什么建议吗?
答案 0 :(得分:1)
您可能希望改为UNION
。
SELECT ce.email, count(*) AS TOTAL_FACILITIES
FROM table1 AS ce
GROUP BY ce.email
UNION
SELECT ca.emails, count(*) AS TOTAL_FACILITIES
FROM table2 AS ca
GROUP BY ca.emails
ORDER BY TOTAL_FACILITIES DESC
更好的解决方案是在聚合之前联合它。
SELECT email, COUNT(*) AS TOTAL_FACILITIES
FROM (
SELECT facilities, email
FROM table1
UNION ALL
SELECT facilities, email
FROM table2
)
GROUP BY email
ORDER BY TOTAL_FACILITIES DESC
答案 1 :(得分:0)
我认为你正在寻找这样的东西:
SELECT A.emails, COUNT(*) as total_facilities
FROM
(SELECT * FROM table1 UNION ALL SELECT * FROM table2) A
GROUP BY A.emails
ORDER BY COUNT(*) DESC;