我目前的系统中有两个表,其中包含当前的电子邮件,还有一个我创建并导出全局通讯簿中的所有电子邮件地址的表,以及一个BIT值,即主电子邮件地址和用户ID值。 我使用子查询编写了一个查询来查找应该更改的电子邮件地址,但是我应该能够在不使用子查询的情况下执行此操作,但无法弄清楚如何操作?
有没有人知道如何在不使用子查询的情况下更好地完成这项工作?
我有什么工作,但我想学习如何更好地编写SQL。
我虽然本应该能够使用OVER(Partition BY Member_ID)和MAX(CAST([primary] AS int))来做到这一点,但花了几个小时试图找出它并且是不合适的。
User_Emails
{
email varchar(75)
}
eg:
User_Emails
bob@oldemail.com
sue@evenolderemail.com
jim@otheremail.com
bill@oldemail.com
...
Global_Address_Book
{
Member_ID int
primary BIT
email_address varchar(75)
}
eg:
Member_ID | primary | email_address
1 | 1 | bob@newemail.com
1 | 0 | bob@reallyoldemail.org
1 | 0 | bob@oldemail.com
2 | 1 | sue@newemail.com
2 | 0 | sue@oldemail.com
2 | 0 | sue@reallyoldemail.org
2 | 0 | sue@evenolderemail.com
3 | 1 | bill@newemail.com
3 | 0 | bill@oldemail.com
4 | 1 | jan@alternativeemail.com
...
SELECT Changed_Email_list.email AS Old_Email, New_Email_List.email_address AS New_Email
FROM (SELECT Member_ID, email
FROM [Database].[Global_Address_Book] INNER JOIN [Database].[User_Emails]
ON [Global_Address_Book].[email_address] = [User_Emails].[email]) AS
Changed_Email_list LEFT JOIN
(SELECT Member_ID, email_address
FROM [Database].[Global_Address_Book]
WHERE [primary] = 1) AS New_Email_List
ON Changed_Email_list.Member_ID = New_Email_List.Member_ID
答案 0 :(得分:2)
这应该是我猜的
select UserEmails.Email as OldEmail,GAB.Email as NewEamil
from UserEmailsfromAddressBook
inner join UserEmails on UserEmails.Email=UserEmailsfromAddressBook.Email
and isprimary =0
inner join UserEmailsfromAddressBook GAB on GAB.memberId=UserEmailsfromAddressBook.memberID
and GAB.isprimary=1
中的测试脚本