给定两个表(每个表中的行是不同的):
1) x | y z 2) x | y z
------- --- ------- ---
1 | a a 1 | a a
1 | b b 1 | b b
2 | a 1 | c
2 | b 2 | a
2 | c 2 | b
2 | c
有没有办法选择第一个表的x
列中的值,y
列中x
列的值子集与z
列的值完全匹配在第二个表的1)
列中?
如果1
,预期结果为c
。如果将2
添加到第二个表格,则预期结果为2)
在no record
的情况下,预期结果为c
,因为第一个表中的子集都不匹配第二个表中的子集。如果将1, 2
添加到第二个表格,则预期结果为except
。
我已尝试使用intersect
和intersect
将第一个表的子集与第二个表进行比较,这样可以正常工作,但{{1}}部分需要太长时间,我可以弄清楚原因(第一张表有大约10.000条记录,第二张大约有10条记录)。
答案 0 :(得分:7)
SELECT
table1.x
FROM
table1
INNER JOIN
table2
ON table1.y = table2.z
GROUP BY
table1.x
HAVING
COUNT(*) = (SELECT COUNT(*) FROM table2 AS lookup)
AND COUNT(*) = (SELECT COUNT(*) FROM table1 AS lookup WHERE x = table1.x)
答案 1 :(得分:1)
其中一个会做
select
t1.x
from
table1 as t1 inner join table2 as t2 on t1.x=t2.x
group by t1.x
having count(distinct t1.x)=count(distinct t2.x)
select
t1.x
from
table1 as t1 inner join table2 as t2 on t1.x=t2.x
group by t1.x
having count(distinct t1.x)=(select count(distinct x) from table2)