【问题标题】:Insert Foreign Records using IDs from Insert Into Query in PostgreSQL使用 PostgreSQL 中的 Insert Into Query 中的 ID 插入外部记录
【发布时间】: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


【解决方案1】:

如果我理解正确,您可以使用 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;

【讨论】:

  • 这正是我需要的结构,WITH AS 和 RETURNING * 模式。我需要做的就是在最后调整标准,它起作用了,谢谢!
猜你喜欢
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多