SQL:比较2个表并说明是否找到了数据



我是SQL的新手,所以如果这是一个愚蠢的问题,请原谅我。

我有两个表,一个是用户列表,另一个是保存电子邮件历史数据的表。

用户表:

userID fName  lName ...
1      John   Smith
2      Jane   Doe
3      Kevin  Cooper

电子邮件历史记录表:

emailID userID subject sendDate ...
1       6      welcome 2020-10-17
2       3      hello   2020-10-20
3       7      welcome 2020-10-23

我想做一些选择语句,根据某种搜索查询将表1中的每个客户与表2中的每个电子邮件进行比较(在这种情况下,subject="hello"和sendDate="2020-10-20"(,并返回如下内容:

返回查询:

userID  fName  lName  ...  emailSent?
1       John   Smith  ...  No
2       Jane   Doe    ...  No
3       Kevin  Cooper ...  Yes
一个选项使用exists和相关的子查询:
select u.*, 
exists (
select 1
from emailhistory eh
where eh.userid = u.userid and eh.subject = 'hello' and eh.senddate = '2020-20-20'
) emailSent
from users u

这将在列emailSent中为您提供0/1值,其中1表示存在匹配。与left join方法相比,优点在于它没有";乘以";如果在历史记录表中找到多个匹配项,则显示用户行。

为了提高性能,请考虑emailhistory(userid, subject, senddate)上的索引。

您可以在上加入电子邮件表,将日期和主题标准放入where子句中:

SELECT
u.userid,
u.fname,
u.lname,
case when eh.emailid is null then 'No' else 'Yes' end as emailsent
FROM
users u
LEFT JOIN 
emailhistory eh 
ON 
u.userid = eh.emailid AND
eh.subject = 'hello' AND
eh.senddate = '2020-10-20'

从概念上讲,这会将电子邮件表筛选到主题和日期,然后将这些记录连接到用户表中。你从用户那里得到每一行,从电子邮件历史记录中只得到与userid匹配的行,并且有该主题/日期。然后,您可以检查emailid(联接的一个键(是否为null;唯一可以为空的方法是,如果在该日期没有向该用户发送带有该主题的电子邮件

相关内容

最新更新