我有两个类型兼容的表; A和B。我想要一个SQL查询,该查询将告诉我B的所有元素是否也是A的元素。
示例1:
Table A
c1 | c2
--------+--------
"Hello" | "World"
"Hello" | "Kitty"
"Hello" | "pretty"
Table B
c1 | c2
--------+--------
"Hello" | "World"
"Hello" | "Kitty"
expected: TRUE
示例2:
Table A
c1 | c2
--------+--------
"Cat" | 1
"Gato" | 2
"Neko" | 3
Table B
c1 | c2
--------+--------
"Cat" | 1
"Chat" | 4
expected: FALSE
答案 0 :(得分:0)
一种方法可以是联合和左联接
select case when t2.col is not null then 'all elements of B are also elements of A.' else null end from
(
select distinct c1 as col from A
union
select distinct c2 from A
) t1
left join
(
select distinct c1 as col from B
union
select distinct c2 from B
) t2 on t1.col=t2.col
答案 1 :(得分:0)
此查询将尝试同时使用列b
和a
将表c1
中的所有值与表c2
进行匹配。
如果它们匹配,则查询的equals
将为true
,否则为false
。
工作示例:https://www.db-fiddle.com/f/d1N7ZaUSdogoTVCYefpdc1/1
SELECT COUNT(*) = 0 AS equal
FROM b
LEFT JOIN a USING (c1, c2)
WHERE a.c1 IS NULL;