我可以使用以下查询比较两个表缺少数据
SELECT S.DEVID,S.INPUTID,S.PRI,S.CCID FROM [DEVICE-SECURITY].DBO.DEVICE_LINK S
WHERE HID = 4
EXCEPT
SELECT T.DEVID,T.INPUTID,T.PRI,T.CCID FROM DEVICE-CONFIG.DBO.DEVICE_LINK T
WHERE HID = 1
上面的查询返回我的源中不存在的四行 表
现在我正在尝试使用子查询来实现相同的结果
SELECT S.DEVID,S.INPUTID,S.PRI,S.CCID ,
CASE WHEN S.HID = '4' THEN '1' END AS HID
FROM [DEVICE-SECURITY].DBO.DEVICE_LINK S
WHERE S.HID= 4 AND NOT EXISTS (
SELECT T.DEVID,T.INPUTID,T.PRI,T.CCID FROM DEVICE-CONFIG.DBO.DEVICE_LINK T
WHERE T.HID = 1 )
它不返回任何行。
如何使用子查询
获得相同的结果答案 0 :(得分:1)
等效的不存在查询
SELECT S.DEVID,S.INPUTID,S.PRI,S.CCID FROM [DEVICE-SECURITY].DBO.DEVICE_LINK S
WHERE HID = 4
AND NOT EXISTS (
SELECT 1 FROM DEVICE-CONFIG.DBO.DEVICE_LINK T
WHERE HID = 1
AND T.DEVID = S.DEVID AND T.INPUTID = S.INPUTID
AND T.PRI = S.PRI AND T.CCID = S.CCID
)
答案 1 :(得分:1)
您有两个选择
您可以执行不在过滤器中,然后子查询不必连接到外部
SELECT S.DEVID,S.INPUTID,S.PRI,S.CCID , CASE WHEN S.HID = '4' THEN '1' END AS HID FROM [DEVICE-SECURITY].DBO.DEVICE_LINK S WHERE S.HID= 4 AND S.DEVID+S.INPUTID+S.PRI+S.CCID NOT in ( SELECT T.DEVID+T.INPUTID+T.PRI+T.CCID FROM DEVICE-CONFIG.DBO.DEVICE_LINK T WHERE T.HID = 1 )
或者您可以保持不存在并将子查询连接到您要比较的所有字段的主要
SELECT S.DEVID,S.INPUTID,S.PRI,S.CCID , CASE WHEN S.HID = '4' THEN '1' END AS HID FROM [DEVICE-SECURITY].DBO.DEVICE_LINK S WHERE S.HID= 4 AND NOT exists ( SELECT 1 FROM DEVICE-CONFIG.DBO.DEVICE_LINK T WHERE T.HID = 1 and T.DEVID+T.INPUTID+T.PRI+T.CCID=S.DEVID+S.INPUTID+S.PRI+S.CCID)