我有两张桌子:
T1(IDa,IDb)
:有这样的数据
IDa IDb 1 2 3 4 5 6 7 8
和T2(IDc,IDd)
:使用此类数据
IDc IDd 1 2 4 5 3 6 7 8
并且每个表的标识是ID对:
问题是:如何从两个表中检索“不匹配”记录??? 在这种情况下,
我可以使用字符串和连接来做到这一点。 有没有人使用内连接或任何其他方法?
答案 0 :(得分:5)
DECLARE @Result nvarchar(max)
SELECT @Result = ISNULL(@Result + '$','') +
CAST(ISNULL(IDa,IDc) AS VARCHAR(5)) + ',' +
CAST(ISNULL(IDb,IDd) AS VARCHAR(5))
FROM T1 FULL OUTER JOIN T2
ON T1.IDa = T2.IDc AND T1.IDb = T2.IDd
WHERE T1.IDa IS NULL OR T2.IDc IS NULL
修改当然,如果不需要$
和,
,请使用
SELECT ISNULL(IDa,IDc), ISNULL(IDb,IDd)
FROM T1 FULL OUTER JOIN T2
ON T1.IDa = T2.IDc AND T1.IDb = T2.IDd
WHERE T1.IDa IS NULL OR T2.IDc IS NULL
或者换句话说,只是为了踢(MS SQL Server 2005 +)
SELECT IDa, IDb from T1
EXCEPT
SELECT IDc, IDd from T2
UNION ALL
(
SELECT IDc, IDd from T2
EXCEPT
SELECT IDa, IDb from T1
)
答案 1 :(得分:3)
select IDa, IDb from T1
where not exists (select 1 from T2 where T2.IDc = T1.IDa and T2.IDd = T1.IDb)
union all
select IDc, IDd from T2
where not exists (select 1 from T1 where T2.IDc = T1.IDa and T2.IDd = T1.IDb)