获取表 A 中在表 b 中没有外键条目的所有元素

wmo*_*kal 1 sql sql-server foreign-keys

所以我有2张桌子。表 B 与表 A 具有外键关系。

例如。

Table A
id        column 1        column 2
1           some            thing
2           foo             bar
3           hello           world
4           this            that
5            x                y

Table B
id        Table A id        testcolumn
1             5               blah
2             5               blah
3             2               aggg
4             2               aggg
5             4                a
6             4                b
7             4                c
Run Code Online (Sandbox Code Playgroud)

我想要的是从表 A 中选择所有元素,其中表 B 中没有外键匹配。在示例的情况下,我想从表 A 中选择 id 为 1 和 3 的行。我该怎么做在 MS SQL 数据库中实现这一点?

The*_*ler 8

您可以使用反连接:

select a.*
from a
left join b on a.id = b.table_a_id
where b.table_a_id is null
Run Code Online (Sandbox Code Playgroud)