【发布时间】:2021-12-18 22:42:45
【问题描述】:
我的 PostgreSQL 12 数据库中有 2 个具有一对多关系的永久表(thing 和 thing_identifier)。第二个——thing_identifier——有一个引用thing的列,这样thing_identifier可以为给定的thing保存多个外部标识符:
CREATE TABLE IF NOT EXISTS thing
(
thing_id SERIAL PRIMARY KEY,
thing_name TEXT, --this is not necessarily unique
thing_attribute TEXT --also not unique
);
CREATE TABLE IF NOT EXISTS thing_identifier
(
id SERIAL PRIMARY KEY,
thing_id integer references thing (thing_id),
identifier text
);
我需要在thing 和thing_identifier 中插入一些新数据,这两个数据都来自我使用COPY 创建的表,用于将大型CSV 文件的内容拉入数据库,类似于:
CREATE TABLE IF NOT EXISTS things_to_add
(
id SERIAL PRIMARY KEY,
guid TEXT, --a unique identifier used by the supplier
thing_name TEXT, --not unique
thing_attribute TEXT --also not unique
);
样本数据:
INSERT INTO things_to_add (guid, thing_name) VALUES
('[111-22-ABC]','Thing-a-ma-jig','pretty thing'),
('[999-88-XYZ]','Herk-a-ma-fob','blue thing');
目标是让things_to_add 中的每一行在thing 和thing_identifier 中产生一个新行,如下所示:
thing:
| thing_id | thing_name | thing attribute |
|----------|---------------------|-------------------|
| 1 | thing-a-ma-jig | pretty thing
| 2 | herk-a-ma-fob | blue thing
thing_identifier:
| id | thing_id | identifier |
|----|----------|------------------|
| 8 | 1 | '[111-22-ABC]' |
| 9 | 2 | '[999-88-XYZ]' |
我可以使用 CTE INSERTstatement(与 RETURNING thing_id)来获得 thing_id 由 INSERT 上的 thing 产生,但我不知道如何获得 两者 即thing_id 来自INSERT 上的thing 原来的guid 来自things_to_add,这需要进入thing_identifier.identifier。
需要明确的是,thing 中唯一保证唯一的列是 thing_id,things_to_add 中唯一保证唯一的列是 id(我们不想存储)和 guid (这是我们在thing_identifier.identifier 中想要的),所以在thing 上的INSERT 之后没有任何方法可以加入thing 和things_to_add。
【问题讨论】:
标签: postgresql sql-insert common-table-expression sql-returning