sql 不同于多个 select select

sql distinct select from multiple select

加入以下三个 select 并获得不重复的 contact.id 的最佳方法是什么?

有什么想法吗?

 SELECT distinct ct.id
  FROM [Customer].[dbo].[Contact] ct 
  left join [Customer].[dbo].[HN_Customer_ids] hnids 
       on ct.id = hnids.contact_id 
  left join [CustomerTransactions].[dbo].[Transaction_Header] trh 
       on trh.Customer_ID = hnids.HN_customer_id
 where trh.actual_transaction_date > '20120218'

结果:231360

  SELECT count(distinct(contact_id))
  FROM [Customer].[dbo].[Restaurant_Attendance]
  where ( created > '2012-02-18 00:00:00.000' or modified > '2012-02-18 00:00:00.000') 
    AND 

结果:167128

 SELECT distinct aaa.id
  FROM [Customer].[dbo].[Contact] aaa 
  left join [Customer].[dbo].[Wifinity_Devices] bbb 
       on aaa.wifinity_uniqueID = bbb.[CustomerUniqueID]
  and startconnection > '2012-02-17'

结果:77290

使用联合

SELECT ct.id
  FROM [Customer].[dbo].[Contact] ct 
  left join [Customer].[dbo].[HN_Customer_ids] hnids on ct.id = hnids.contact_id 
  left join [CustomerTransactions].[dbo].[Transaction_Header] trh on trh.Customer_ID = hnids.HN_customer_id
  where trh.actual_transaction_date > '20120218'
union 
 SELECT  contact_id 
  FROM [Customer].[dbo].[Restaurant_Attendance]
  where ( created > '2012-02-18 00:00:00.000' or modified > '2012-02-18 00:00:00.000')
union 
 SELECT aaa.id
  FROM [Customer].[dbo].[Contact] aaa left join [Customer].[dbo].[Wifinity_Devices] bbb on aaa.wifinity_uniqueID = bbb.[CustomerUniqueID]
  and startconnection > '2012-02-17'

使用union。所以:

SELECT ct.id
FROM [Customer].[dbo].[Contact] ct join
     [Customer].[dbo].[HN_Customer_ids] hnids
     on ct.id = hnids.contact_id join
     [CustomerTransactions].[dbo].[Transaction_Header] trh
     on trh.Customer_ID = hnids.HN_customer_id
WHERE trh.actual_transaction_date > '20120218'
UNION
SELECT contact_id
FROM [Customer].[dbo].[Restaurant_Attendance]
WHERE (created > '2012-02-18 00:00:00.000' or
       modified > '2012-02-18 00:00:00.000')
UNION
SELECT aaa.id
FROM [Customer].[dbo].[Contact] aaa ;

第一个和第三个查询中的 left join 是不必要的。首先,where 无论如何都会撤消 left join。在第三个中,您从第一个 table 中选择一个 idleft join 不进行过滤。

假设所有查询 运行 针对同一个联系人 table,您对左外部联接的使用实际上导致第三个查询 return all 联系人。除非第二个查询可以添加 contact_ids not found in the Contact table,最终结果相当于:

select /* distinct, if not a pk */ contact_id from Customer.dbo.Contact

您的行数表明这些可能实际上是来自不同数据库的 table。是这样吗?