【问题标题】:How to join two table and using the second table to override the first one?如何连接两个表并使用第二个表覆盖第一个表?
【发布时间】:2021-08-23 15:34:03
【问题描述】:

我正在开发一个待办事项应用程序,其中多个项目共享一个预配置的清单,我想要的是能够根据每个项目包含的清单进行修改。

我想到的是有 2 个单独的表:1 个用于共享表,1 个用于每个项目的修改,就像这样

CREATE TABLE checklist (
    id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
    title text NOT NULL,
    description text NOT NULL,
);

CREATE TABLE modification (
    project_uuid uuid,
    id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
    title text NOT NULL,
    description text NOT NULL,
);

每个项目都有自己的清单,基于用户可以修改的预配置清单,对共享清单所做的任何修改都将反映到所有项目中。

有没有办法使用第二个“修改”表在“清单”表的顶部进行修改?如果在“修改”中没有找到某一行,它将从“清单”中获取它,并且如果两个表中都存在一行,则“修改”中的行将覆盖“清单”中的行?

例如,如果我有:

SELECT * FROM checklist;
id | title  | description
---+--------+-------------
 1 | Item 1 | Dummy item
 2 | Item 2 | Dummy item

SELECT * FROM modification;
project_uuid | id | title  | description          |
-------------+----+--------+----------------------+
  1          | 2  | Item 2 | Modified description |

我想要这个结果

 id |  title | description          |
----+--------+----------------------+
  1 | Item 1 | Dummy item           |
  2 | Item 2 | Modified description |

提前致谢

【问题讨论】:

    标签: sql database postgresql database-design


    【解决方案1】:

    使用左连接和coalesce()函数:

    select  c.id, 
            coalesce(m.title, c.title)             as title, 
            coalesce(m.description, c.description) as description
      from checklist c 
           left join modification m on c.id=m.id
    

    【讨论】:

      猜你喜欢
      • 2016-07-08
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 2018-05-05
      相关资源
      最近更新 更多