如何制作这个sql语句

时间:2010-07-01 08:44:47

标签: sql tsql

我有两张桌子:
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对:

  • T1,身份是IDa和IDb
  • T2是IDc和IDd

问题是:如何从两个表中检索“不匹配”记录??? 在这种情况下,

  • 匹配的是1,2和7,8
  • “不匹配”是:3,4 $ 5,6 $ 4,5 $ 3,6

我可以使用字符串和连接来做到这一点。 有没有人使用内连接或任何其他方法?

2 个答案:

答案 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)