是否可以 return 在 SQL 中插入多行的 ID?

Is it possible to return the IDs of a multi row insert in SQL?

使用下面的语句,我可以将多行插入 table。如果标签已经存在则什么也不会发生,如果它不存在则创建行。

INSERT INTO tags (name) VALUES ('this'),('is'),('my'),('interest'),('list'),('running'),('pokemongo'),('fighting'),('eating') ON CONFLICT DO NOTHING;

是否可以 return 所有这些值的 ID 是否存在?

我正在使用 python psycopg2 和 postgres 9.5。

INSERT INTO 
    tags (name) 
VALUES 
    ('this'),('is'),('my'),('interest'),('list'),('running'),('pokemongo'),('fighting'),('eating') 
ON CONFLICT DO NOTHING 
RETURNING ID; # <== this is what you need.

编辑: 是的,使用此解决方案,您只会获得插入行的 ID。

如果您需要所有 ID,则必须进行另一个查询:

select ID from tags where name in ('this', 'is', 'my', 'interestest', 'list', '...')

这可以在使用 WITH 块的一个查询中完成(请参阅 WITH and SELECT 上的 PostgreSQL 文档)。例如:

WITH t1 (c1) AS ( VALUES ('this'),('is'),... ),
t2 AS (SELECT id FROM tags WHERE name IN (SELECT c1 FROM t1) ),
t3 AS (INSERT INTO tags (name) SELECT c1 FROM t1 ON CONFLICT DO NOTHING RETURNING id)
SELECT id from t2
UNION
SELECT id from t3;

您也可以将 ON CONFLICT DO NOTHING 替换为 WHERE c1 NOT IN (SELECT name FROM tags)。这将在不依赖唯一索引引起的冲突的情况下工作。