【发布时间】:2017-09-07 22:57:04
【问题描述】:
我的目标是将“Book”表中的每一行(如果它有一个非空的 publish_date)分成两个“Book”行,一个是原始行,一个是具有新的自动递增 id 的新行,一个新的publish_type,没有 publish_date(不相关)和相同的 isbn。
我写了一条 SQL 语句来执行此操作,但诀窍是现在,我需要获取每个新行的 id,并根据每个原始 Book 的 Origin 记录在“Origin”表中创建新的外部记录 - 我基本上需要复制 Origin 记录,以便每个新 Book 记录映射到 Origin 表中正确的(原始的)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;
例如..
/* 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 from 语句中,该语句可以使用前一个查询的 id 来复制与原始书行键相关的外来记录,但我无法确定如何携带超过输入。
【问题讨论】:
-
因为修改书籍而复制客户和国家/地区听起来不对。
-
你说得对,customer_id 实际上应该是 book_id。
标签: sql postgresql