我有多行数据。这只是一些组成的数据,以便做一个简单的例子。
name
,age
和location
。persons
和locations
,其中locations
的FK为persons
。COPY
(在我的实际示例中,我使用的是NPQSQL for .NET,我认为这是插入大量数据的最快方式)。所以我会在一个事务中执行以下操作(不是100%确定语法,而不是现在在我的计算机上):
-- Create a temp table
DROP TABLE IF EXISTS tmp_x;
CREATE TEMPORARY TABLE tmp_x
(
name TEXT,
age INTEGER,
location TEXT
);
-- Read the data into the temp table
COPY tmp_x (name, age) FROM STDIN (FORMAT BINARY);
-- Conditionally insert the data into persons
WITH insertedPersons AS (
INSERT INTO persons (name, age)
SELECT name, age
FROM tmp_x tmp
LEFT JOIN persons p ON p.name = tmp.name
WHERE
p IS NULL
AND tmp.age >= 18
RETURNING id, name
),
-- Use the generated ids to insert the relational data into locations
WITH insertedLocations AS (
INSERT INTO locations (personid, location)
SELECT ip.id, tmp.location
FROM tmp_x tmp
INNER JOIN insertedPersons ip ON ip.name = tmp.name
),
DROP TABLE tmp_x;
INNER JOIN insertedPersons ip ON ip.name = tmp.name
。如果name
不是唯一的,该怎么办?我可以使用新的人ID更新tmp_x
并使用它吗?