gpt4 book ai didi

sql - 如何使用 last_insert_rowid 插入多行?

转载 作者:行者123 更新时间:2023-12-03 16:00:10 24 4
gpt4 key购买 nike

假设我有一个包含两个表的数据库 PersonsPhoneNumbers ,其中PhoneNumbers表有一个指向 Persons 的外键.如果我想在单笔交易中插入一个有电话号码的人,我可以写一个这样的查询:

BEGIN TRANSACTION;
INSERT INTO Persons(Name) VALUES(...);
INSERT INTO PhoneNumbers(PersonForeignKey, Number) VALUES(last_insert_rowid(), ...);
END TRANSACTION;

但是如果我想插入一个有多个电话号码的人怎么办?显而易见的方法:
BEGIN TRANSACTION;
INSERT INTO Persons(Name) VALUES(...);
INSERT INTO PhoneNumbers(PersonForeignKey, Number) VALUES(last_insert_rowid(), ...);
INSERT INTO PhoneNumbers(PersonForeignKey, Number) VALUES(last_insert_rowid(), ...);
INSERT INTO PhoneNumbers(PersonForeignKey, Number) VALUES(last_insert_rowid(), ...);
END TRANSACTION;

当然不行,因为对于第二个电话号码, last_insert_rowid()将返回第一个电话号码的 rowid 而不是人。

有没有办法使用基本 SQL(特别是 SQLite)来做到这一点?

结论

显然,没有直接的方法可以做到这一点。我根据@Michal Powaga 的建议和其他一些基于临时表的想法做了一些基准测试,最快的方法似乎是这样的:
CREATE TEMPORARY TABLE IF NOT EXISTS Insert_PhoneNumbers(PersonForeignKey INTEGER, PhoneNumber VARCHAR);
DELETE FROM Insert_PhoneNumbers;
INSERT INTO Insert_PhoneNumbers(PhoneNumber) VALUES ('Phone 1');
INSERT INTO Insert_PhoneNumbers(PhoneNumber) VALUES ('Phone 2');

INSERT INTO Persons(Name) VALUES(...);

UPDATE Insert_PhoneNumbers SET PersonForeignKey=last_insert_rowid();

INSERT INTO PhoneNumbers(PersonForeignKey, Number)
SELECT PersonForeignKey, PhoneNumber
FROM Insert_PhoneNumbers

创建和更新临时表似乎非常快(与对 Persons 或 PhoneNumbers 表的查询相比)并且插入速度不取决于数据库中已有的人数/电话号码,所以这就是我选择的解决方案.

最佳答案

您可以在人员插入临时表后存储 last_insert_rowid() ,或者这也可能有效:

BEGIN TRANSACTION;
INSERT INTO Persons(Name) VALUES(...);

INSERT INTO PhoneNumbers(PersonForeignKey, Number)
VALUES(last_insert_rowid(), 'number 1');

INSERT INTO PhoneNumbers(PersonForeignKey, Number)
SELECT PersonForeignKey, 'number 2'
FROM PhoneNumbers where PhonePrimaryKey = last_insert_rowid();

INSERT INTO PhoneNumbers(PersonForeignKey, Number)
SELECT PersonForeignKey, 'number 3'
FROM PhoneNumbers where PhonePrimaryKey = last_insert_rowid();

END TRANSACTION;

关于sql - 如何使用 last_insert_rowid 插入多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8039185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com