Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 合并3个表的结果_Sql_Postgresql - Fatal编程技术网

Sql 合并3个表的结果

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), (

我使用的是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);
我希望表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