【问题标题】:Combining results from 3 tables结合 3 个表格的结果
【发布时间】: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      |
+-----------+-----------+-----------+

我什至不确定如何处理此查询:joininner selects 甚至可能是 excludes

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    您可以尝试在table1table2 上使用CROSS JOIN(笛卡尔积),然后在CROSS JOIN 结果集的基础上使用table3 LEFT 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
    

    View on DB Fiddle

    【讨论】:

    • @joao 是的,做笛卡尔产品
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2016-08-31
    • 2018-05-14
    • 1970-01-01
    相关资源
    最近更新 更多