mysql 使用Having表达式连接多个表

k2fxgqgv  于 2022-12-17  发布在  Mysql
关注(0)|答案(2)|浏览(199)

有两个表联系人和阻止条目
表:联系人

Id 
FirstName 
LastName 
Email 
JobTitle

表:阻止的条目

Id 
Email

正在尝试从联系人表中查找多次出现blockedEntries的条目

SELECT email, COUNT(*)  as cc, GROUP_CONCAT( id  SEPARATOR '#') AS ContactIds 
FROM contacts 
where email IN (SELECT email FROM BlockedEntries)
GROUP BY email   
HAVING COUNT(*) > 1

对于计数超过1的条目,是否有任何方法可以获取更多的其他详细信息,如名字、姓氏、电子邮件、职位等
遗憾的是,这两个表之间没有关系,电子邮件是唯一可能的Map。联系表中可以存在一个或多个具有相同电子邮件地址的条目
样本数据

Id  FirstName LastName Email JobTitle

12  sam   j  samj@gmail.com  engineer
23  bos   j  bosj@gmail.com  accountnt
34  cas   j  samj@gmail.com  engineer
33  xxx   j  bosj@gmail.com  fied
55  dfe   c  dfe@gmail.com   student

Table: BlockedEntries

Id  Email              CreateDate
1    samj@gmail.com     09/12/2020 19:30:20
2    bosj@gmail.com     09/12/2020 19:30:20
3    dfe@gmail.com       09/12/2020 19:30:20

Result expecting 

email              id  firstname lastName jobtitle 

samj@gmail.com    12  sam   j     engineer
samj@gmail.com    34  bos   j     accountnt
bosj@gmail.com    23  cas   j      engineer
bosj@gmail.com    33  xxx   j      fied

dfe@gmail.com only 1 instance and no need to add this to result set
b4wnujal

b4wnujal1#

在MySQL 8+中,我将使用COUNT()作为分析函数:

WITH cte AS (
    SELECT *, COUNT(*) OVER (PARTITION BY email) email_cnt
    FROM contacts
)

SELECT c.Id, c.FirstName, c.LastName, c.Email, c.JobTitle
FROM cte c
WHERE email_cnt > 1 AND
      EXISTS (
          SELECT 1
          FROM BlockedEntries be
          WHERE be.email = c.email
      );
mpbci0fu

mpbci0fu2#

根据您的数据示例,您只需要两个内部连接,一个与BlockedEntries连接,它将获取BlockedEntries和Contact表之间的所有相关电子邮件,另一个与子查询连接,它将多次获取Contact表上的电子邮件。
试试看:

select c.Id,
       c.FirstName,
       c.LastName,
       c.Email,
       c.JobTitle
from Contact c
inner join BlockedEntries be on be.Email=c.Email  
inner join (select Email
            from Contact
            group by Email
            having count(*)>1 
          ) as cnt on cnt.Email=c.Email;

https://dbfiddle.uk/P9Y4RHfu

相关问题