[英]PostgreSQL insert into multiple tables, using foreign key from first insertion in the second insertion
I'm trying to take an existing table and create two. 我正在尝试采用现有表并创建两个表。 I have a
sections
table that has a file_url
, and now I need to move that into url
field on media_files
table. 我有一个具有
file_url
的sections
表,现在我需要将其移到media_files
表的url
字段中。 Also, I want to populate attachments
table that acts as a has_many :through
(in Rails) which means it keeps track of the foreign key relationships of media_file_id
and section_id
. 另外,我想填充充当
has_many :through
的attachments
表(在Rails中),这意味着它可以跟踪media_file_id
和section_id
的外键关系。
The closest that I've gotten is this: 我得到的最接近的是:
WITH ids AS (
INSERT INTO media_files (url, mimetype)
SELECT file_url, 'image/jpeg'
FROM sections
WHERE file_url IS NOT NULL
RETURNING id AS media_file_id, sections.id AS section_id
)
INSERT INTO attachments (media_file_id, section_id)
SELECT media_file_id, section_id
FROM ids
but I'm getting this error: 但我收到此错误:
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "sections"
LINE 6: RETURNING id AS media_file_id, sections.id AS sectio...
which makes sense, but I'm not sure how to grab the section_id
. 这很有意义,但是我不确定如何获取
section_id
。
Is there a way to get this working? 有没有办法让这个工作? Maybe there's a better, alternative method?
也许有更好的替代方法?
Edit: Here's a link to SQL Fiddle 编辑:这是SQL Fiddle的链接
I can only think of using an additional join in the outer insert: 我只能想到在外部插入中使用其他联接:
WITH ids AS (
INSERT INTO media_files (url, mimetype)
SELECT file_url, 'image/jpeg'
FROM sections
WHERE file_url IS NOT NULL
RETURNING id AS media_file_id, url AS file_url
)
INSERT INTO attachments (media_file_id, section_id)
SELECT ids.media_file_id, s.id
FROM ids
JOIN sections s ON s.file_url = ids.file_url;
SQLFiddle: http://sqlfiddle.com/#!15/6fcaf/4 SQLFiddle: http ://sqlfiddle.com/#!15/6fcaf/4
If you want to avoid problems with duplicates you should use a DISTINCT
clause in the first INSERT
. 如果要避免重复项问题,则应在第一个
INSERT
使用DISTINCT
子句。 This will make two sections point to the same media_file but it should be more than okay. 这将使两个部分指向相同的media_file,但应该还可以。 (Upgraded from @a_horse_with_no_name answer)
(从@a_horse_with_no_name答案升级)
WITH ids AS (
INSERT INTO media_files (url, mimetype)
SELECT DISTINCT file_url, 'image/jpeg'
FROM sections
WHERE file_url IS NOT NULL
RETURNING id AS media_file_id, url AS file_url
)
INSERT INTO attachments (media_file_id, section_id)
SELECT ids.media_file_id, s.id
FROM ids
JOIN sections s ON s.file_url = ids.file_url;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.