使用PostgreSQL中的插入查询中的ID插入外部记录

时间:2017-09-07 22:57:04

标签: sql postgresql

我的目标是将每一行从“书”中分开。 table(如果它有一个非null的publish_date)分为两个“Book'行,原始行和具有新的自动递增ID的新行,新的publish_type,no publish_date(不相关)和相同的isbn。

我写了一个SQL语句来做到这一点,但诀窍是,现在,我需要获取每个新行的id并在&Origin;'基于每个原始Book的Origin记录的表 - 我基本上需要复制Origin记录,以便每个新的Book记录映射到Origin表中的正确(原始' s)country_codes。

/* Here are the tables */
Book
id | publish_date | publish_type | isbn

Origin
customer id | country_code

Country
id | country_code

/* First query to split book objects into two */
INSERT INTO Book (id, publish_date, publish_type, isbn)
SELECT NULL, 'Published', isbn
FROM Book
WHERE publish_date IS NOT NULL;

e.g ..

/* Before */
Book
id | publish_date | publish_type | isbn
1  | 1/1/2000     |              | 123
2  |              |              | 456
3  | 2/2/2002     |              | 789

Origin
customer id | country_code
1           | US
1           | AR
2           | BR
3           | MX

Country
id | country_code
5  | US
6  | AR
7  | BR
8  | MX
/* After */
Book
id | publish_date | publish_type | isbn
1  | 1/1/2000     |              | 123
2  |              |              | 456
3  | 2/2/2002     |              | 789
4  |              |  Published   | 123
5  |              |  Published   | 789

Origin
customer id | country_code
1           | US
1           | AR
2           | BR
3           | MX
4           | US
4           | AR
5           | MX

Country
id | country_code
5  | US
6  | AR
7  | BR
8  | MX

似乎我需要某种子查询或插入select语句,该语句可以使用以前的查询ID来复制与原始书行键相关的外来原始记录,但我和#39;我无法确定如何结转输入。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您可以使用CTE。诀窍是使用ISBN获取原始origin信息:

with b as (
      INSERT INTO Book (publish_date, publish_type, isbn)
          SELECT NULL, 'Published', isbn
          FROM Book
          WHERE publish_date IS NOT NULL
          RETURNING *
     )
insert into origin (customer_id, country_code)
    select b.id, o.country_code
    from origin o join
         book
         on o.customer_id = book.id join
         b
         on b.isbn = book.isbn and publish_date is null;