Sql 合并3个表的结果
我使用的是Postgres 10,其结构和数据如下:Sql 合并3个表的结果,sql,postgresql,Sql,Postgresql,我使用的是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), (
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和表2的所有组合在表3中没有条目,基本上是这样的结果:
+-----------+-----------+-----------+
| 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 |
+-----------+-----------+-----------+
我甚至不确定如何处理此查询:加入或内部选择或甚至可能排除 您可以尝试在
表1
和表2
上使用交叉联接
(笛卡尔积),然后基于交叉联接
结果集使用表3
左联接
模式(PostgreSQL v9.6)
查询#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
@joao是的,笛卡尔产品
t1id t2id t3id
2 2 null
3 1 null
3 2 null