我正在使用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 |
+-----------+-----------+-----------+
请注意结果如何具有表1和表2中的所有可能组合以及表3中的相应ID。
最终,我希望查询仅返回table3.id为NULL的行:
+-----------+-----------+-----------+
| table1.id | table2.id | table3.id |
+-----------+-----------+-----------+
| 3 | 1 | null |
| 2 | 2 | null |
| 3 | 2 | null |
+-----------+-----------+-----------+
我不确定如何处理此查询:加入或内部选择,甚至排除?
答案 0 :(得分:1)
您可以尝试根据CROSS JOIN
结果集在table1
和table2
上使用table3
(笛卡尔积),然后再使用LEFT JOIN
CROSS JOIN
模式(PostgreSQL v9.6)
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);
查询#1
SELECT t1.id,t2.id,t3.id
FROM table1 t1 CROSS JOIN table2 t2
LEFT JOIN table3 t3
on t3.table1_id = t1.id and t3.table2_id = t2.id
where t3.id is null;
结果
t1id t2id t3id
2 2 null
3 1 null
3 2 null