【问题标题】:Merge a one-to-many and a many-to-many relation when joining tables连接表时合并一对多和多对多关系
【发布时间】:2017-02-23 21:05:59
【问题描述】:

我在 PostgreSQL 9.6 中有一个 things 表和一个 things_persons 表,它们表示事物和人之间的多对多关系。但是每个事物也有一个列owner,代表一对多的关系。

我的问题的最小架构如下:

CREATE TABLE things(
  thing_id SERIAL,
  owner integer
 );

 CREATE TABLE things_persons(
   thing_id integer,
   person_id integer
);

INSERT INTO things VALUES(1,10);
INSERT INTO things VALUES(2,10);
INSERT INTO things_persons VALUES(1,10);
INSERT INTO things_persons VALUES(1,11);
INSERT INTO things_persons VALUES(2,11);

以下查询是我想做的一部分:

SELECT * FROM things
LEFT JOIN things_persons USING(thing_id)

结果是:

| thing_id | owner | person_id |
|----------|-------|-----------|
|        1 |    10 |        10 |
|        1 |    10 |        11 |
|        2 |    10 |        11 |

我真正想做的是将所有者视为只是 things_persons 表中的另一个条目。我想列出与每个事物相关联的每个人,无论他们是所有者还是在 things_persons 表中。

以下代表我想要达到的结果:

| thing_id | person_id |
|----------|-----------|
|        1 |        10 |
|        1 |        11 |
|        2 |        10 |
|        2 |        11 |

对于事物1,所有者也在person_ids中,所以不应该重复。对于事物 2,所有者不在 person_ids 中,所以应该在其中添加。

在这里更改架构不是一个选项,但我想不出一种方法来编写一个可以提供我想要的结果的查询。知道如何编写这样的查询吗?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    我想你只想要一个union 或union all:

    SELECT tp.thing_id, tp.person_id
    FROM things_persons tp 
    UNION ALL
    SELECT t.thing_id, t.owner_id
    FROM things t;
    

    如果您希望查询删除重复项,可以使用 union。

    【讨论】:

    • 谢谢,应该这样做。我不知何故陷入了完全错误的想法。我必须检查这是否也适用于我的非简化实际查询,但乍一看我看不出它不应该的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 2015-03-22
    • 2019-08-22
    • 2016-02-18
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多