我有一张这样的表:
table t1{ida,idb,idc}
我在tabletype变量
中有一个记录列表table t2{idb,idc}
现在,我想检查是否存在t1
与{i}所有t2
相同的任何一组{id}
答案 0 :(得分:1)
好像你想要这样的东西:
DECLARE @t1 TABLE ( ida INT, idb INT, idc INT )
DECLARE @t2 TABLE ( idb INT, idc INT )
INSERT INTO @t1
VALUES ( 1, 1, 1 ),
( 1, 2, 1 ),
( 1, 3, 2 ),
( 2, 1, 1 ),
( 2, 2, 1 ),
( 2, 1, 2 )
INSERT INTO @t2
VALUES ( 1, 1 ),
( 2, 1 ),
( 3, 2 )
SELECT DISTINCT
t1.ida
FROM @t1 t1
WHERE NOT EXISTS ( SELECT *
FROM @t2 t2
WHERE NOT EXISTS ( SELECT *
FROM @t1
WHERE ida = t1.ida
AND idb = t2.idb
AND idc = t2.idc ) )
AND NOT EXISTS ( SELECT *
FROM @t1 tt1
WHERE ida = t1.ida
AND NOT EXISTS ( SELECT *
FROM @t2
WHERE idb = tt1.idb
AND idc = tt1.idc ) )
输出:
ida
1
因此,除了相同匹配的数量之外,这仅返回完全匹配的ida
个值。即以下内容仍然匹配:
( 1, 1, 1 ),
( 1, 2, 1 ),
( 1, 3, 2 ),
( 1, 3, 2 )
答案 1 :(得分:1)
尝试以下查询,该查询使用inner join
查找表t1
和t2
中的匹配行,并显示完全匹配的t1.ida
值
select a.ida
from t1 a inner join t2 b
on a.idb = b.idb and a.idc = b.idc
group by a.ida
having count(1) >= (select count(1) from t2)