我有两个共享一个公共密钥和几个不同列的表。共同密钥是CampaignID
。其中一个表比另一个表略多CampaignID
,我想找出这两个表之间的区别。目前,我使用LEFT OUTER JOIN
和CTE
首先合并这两个表,然后检查前面步骤中派生的NULL
结果集中的CTE
列来计算差异在CampaignID
列中。例如,
WITH CTE_Results
AS (SELECT t1.CampaignID AS cd_CampaignID,
t2.CampaignID AS cod_CampaignID,
t1.NAME,
t2.Vendor
FROM CampaignDetails AS t1
LEFT OUTER JOIN CampaignOnlineDetails AS t2
ON t1.CampaignID = t2.CampaignID)
-- Now that I have CTE result, I'll use another SELECT to find the difference
SELECT cd_CampaignID, cod_CampaignID
FROM CTE_Results
WHERE cod_CampaignID is NULL
但这对我来说似乎效率低下。是否有更有效/更快的方法来比较Microsoft SQL Server中两个表之间特定列的差异?谢谢你的回答!
注意:我一般都是Microsoft SQL Server和SQL的新手。
答案 0 :(得分:2)
如果一个表比另一个表更多,那么bout:
SELECT C1.* FROM CAMPAIGN_WITH_MORE_DATA AS C1
WHERE NOT EXISTS(SELECT * FROM CAMPAIGN_WITH_LESS_DATA AS C2
WHERE C2.CAMPAIGN_ID = C1.CAMPAIGN_ID)
如果其中一个可能有一个广告系列,那么UNION
这个:
SELECT C1.Name AS [Col1],
C1.CAMPAIGN_ID,
'More Campaigns' AS [Source]
FROM CAMPAIGN_WITH_MORE_DATA AS C1
WHERE NOT EXISTS(SELECT * FROM CAMPAIGN_WITH_LESS_DATA AS C2
WHERE C2.CAMPAIGN_ID = C1.CAMPAIGN_ID)
UNION ALL
SELECT C2.Vendor AS [Col1],
C2.CAMPAIGN_ID,
'Less Campaigns' AS [Source]
FROM CAMPAIGN_WITH_LESS_DATA AS C2
WHERE NOT EXISTS(SELECT * FROM CAMPAIGN_WITH_MORE_DATA AS C1
WHERE C1.CAMPAIGN_ID = C2.CAMPAIGN_ID)
答案 1 :(得分:1)
不存在可能比左连接更有效。这也会起作用:
SELECT CampaignID FROM CampaignDetails
EXCEPT
SELECT CampaignID FROM CampaignOnlineDetails
只需按相反的顺序检查反方向。