简体   繁体   English

SQL结合多个表中的两个选择

[英]SQL combine two select across multiple tables

So I've these tables: 所以我有这些表:

Table 1: 表格1:

facilities   emails
Fac 1        fac1@email.com
Fac 2        fac2@email.com
Fac 1 RE     fac1@email.com

Table 2: 表2:

facilities  emails
fac1        fac1@email.com
fac2        fac3@email.com

Now, on those two tables, I am trying to figure out how many facilities are using each address email. 现在,在这两个表上,我试图找出每个地址电子邮件正在使用多少种设施。 I have two sql queries that do just that: 我有两个这样做的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

This gives me the different emails from each table and how many facilities use them. 这给了我每个表不同的电子邮件,以及有多少设施在使用它们。 I'm now trying to combine it into a single call using a join but I can't seem to figure out how to make the count work. 我现在正尝试使用联接将其合并为一个呼叫,但似乎无法弄清楚如何使计数有效。

Any suggestions? 有什么建议么?

You may want to UNION it instead. 您可能要改为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

A better solution is to UNION it before aggregating. 更好的解决方案是在聚合之前对其进行UNION。

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

I think you are looking for something like this: 我认为您正在寻找这样的东西:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM