【发布时间】:2019-02-13 18:13:30
【问题描述】:
我使用的是 Postgres 10,具有以下结构和数据:
create table table1(
id serial primary key
);
create table table2(
id serial primary key
);
create table table3(
id serial primary key,
table1_id int,
table2_id int
);
insert into table1 (id) values (1), (2), (3);
insert into table2 (id) values (1), (2);
insert into table3 (id, table1_id, table2_id) values (1, 1, 1), (2, 1, 2), (3, 2, 1);
我想要在 table3 中没有条目的 table1 和 table2 的所有组合,基本上是这种结果:
+-----------+-----------+-----------+
| table1.id | table2.id | table3.id |
+-----------+-----------+-----------+
| 1 | 1 | 1 |
| 2 | 1 | 3 |
| 3 | 1 | null |
| 1 | 2 | 2 |
| 2 | 2 | null |
| 3 | 2 | null |
+-----------+-----------+-----------+
注意结果如何包含 table1 和 table2 中的所有可能组合,以及 table3 中的相应 id。
最后,我想让查询只返回 table3.id 为 NULL 的行:
+-----------+-----------+-----------+
| table1.id | table2.id | table3.id |
+-----------+-----------+-----------+
| 3 | 1 | null |
| 2 | 2 | null |
| 3 | 2 | null |
+-----------+-----------+-----------+
我什至不确定如何处理此查询:join 或 inner selects 甚至可能是 excludes?
【问题讨论】:
标签: sql postgresql