我有一个从小型数据库中提取联系人列表的 SQL 查询;它可以很好地提取数据。然而,SQL 的问题在于它会根据电子邮件数量和与联系人关联的地址多次列出同一个联系人。
它应该只列出一次。这是我编写的 SQL:
SELECT DISTINCT
Contact_Main.contactid, first_name, last_name, p_title,
prefix, suffix, email, address1, address2,
city, state, zip, Contact_Address_Type.addresstype,
Contact_Email_Types.emailtype,
addressid, emailid, Contact_Address_Type.addresstypeid,
Contact_Email_Types.emailtypeid,
(SELECT COUNT(addressid)
FROM Contact_Address
WHERE contactid = Contact_Main.contactid) as num_addresses,
(SELECT COUNT(emailid)
FROM Contact_Email
WHERE contactid = Contact_Main.contactid) as num_emails
FROM Contact_Main
LEFT JOIN Contact_Email ON Contact_Main.contactid =
Contact_Email.contactid
LEFT JOIN Contact_Email_Types ON Contact_Email_Types.emailtypeid =
Contact_Email.emailtypeid
LEFT JOIN Contact_Address ON Contact_Address.contactid =
Contact_Main.contactid
LEFT JOIN Contact_Address_Type ON Contact_Address_Type.addresstypeid =
Contact_Address.addresstypeid
ORDER BY last_name, first_name;
我确定这是一个简单的修复程序,我需要将其中的某些部分作为子查询,但由于某种原因我无法弄清楚。