如何知道一个元素是否与SQL中另一个表中的每个元素匹配

如何知道一个元素是否与SQL中另一个表中的每个元素匹配,sql,oracle,Sql,Oracle,我在SQL中遇到以下问题: 我有一个表,其中只有一列包含不同的值:[a、B、C、D]例如 在另一个表中,我有两列: 1 | A 1 | C 2 | D 1 | B 2 | D 1 | D ... 我需要返回1,因为它是唯一与另一个表中的每个值匹配的项,我该怎么做?谢谢:)这是解决方案,您可以将第二个表中的行数与第一个表中的行数进行比较, 我使用distinct来确保如果存在重复项,则不会将其计算在内: SELECT id FROM table2 WHERE word in (select

我在SQL中遇到以下问题:

我有一个表,其中只有一列包含不同的值:[a、B、C、D]例如

在另一个表中,我有两列:

1 | A
1 | C
2 | D
1 | B
2 | D
1 | D
...

我需要返回1,因为它是唯一与另一个表中的每个值匹配的项,我该怎么做?谢谢:)

这是解决方案,您可以将第二个表中的行数与第一个表中的行数进行比较, 我使用distinct来确保如果存在重复项,则不会将其计算在内:

SELECT id 
FROM 
table2 
WHERE word in (select word from table1)
GROUP BY id
HAVING COUNT(DISTINCT word) = ( SELECT COUNT(*) FROM table1)

您可以使用聚合:

select col1
from table1 t1
where col2 in (select col2 from table2)
group by col1
having count(*) = (select count(*) from table2);

这假设
col1
/
col2
列在
table1
中是唯一的。如果没有,请在
having
子句中使用
count(distinct)

另一个选项是使用
左外连接和分析函数,如下所示:

Select id, word from
(Select t2.*,
       Count(distinct t1.word) over () as total_words,
       Count(distinct t2.word) over (partition by t2.id) as total_words_per_id
  From table1 t1
  Left Join table2 t2 on t1.word = t2.word)
Where total_words = total_words_per_id

表2中的值是否唯一?你试过什么?