进行查询,以基于两个表查找缺失的组合。
letter
======
a
b
c
d
e
name letter
===== ======
chris a
chris b
chris d
james b
james d
要查找当前不存在的所有名称/字母组合
name letter
===== ======
chris c
chris e
james a
james c
james e
尝试了以下SQL
select name, (select letter
from letters where letter not in
(select letter from nameletter nl2 where nl2.name = nl.name))
from nameletter nl
但是收到了错误消息,即子查询返回了多个值。
create table letters (letter varchar(1))
insert into letters
values ('a'),('b'),('c'),('d'),('e')
create table nameletter (name varchar(max),letter varchar(1))
insert into nameletter values
('chris', 'a'),('chris', 'b'),('chris', 'd'),('james', 'b'),('james','d')
答案 0 :(得分:3)
使用cross join
生成行,然后使用left join
(或not in
或not exists
)获得不匹配的行:
select n.name, l.letter
from (select distinct name from nameletter) n cross join
letter l left join
nameletter nl
on nl.name = n.name and nl.letter = l.letter
where nl.name is null;