我正在使用 Python 在 mysql insert ignore into.......
中运行查询
运行查询后,我想知道行的主键。我知道有查询
SELECT LAST_INSERT_ID();
但我不确定它是否适用于 insert ignore
最好的方法是什么?
最佳答案
The documentation对于 LAST_INSERT_ID()
说:
If you use INSERT IGNORE and the row is ignored, the AUTO_INCREMENT counter is not incremented and LAST_INSERT_ID() returns 0, which reflects that no row was inserted.
了解这一点,您可以将其变成一个多步骤过程:
- 插入忽略
- 如果 LAST_INSERT_ID(),则完成(插入新行)
- else SELECT your_primary key FROM yourtable WHERE(您插入的数据的唯一约束)
以美国各州为例:
id | abbrev | other_data
1 | AL | ...
2 | AK |
UNIQUE KEY abbr (abbrev)
现在,插入一个新行:
INSERT IGNORE INTO `states` (`abbrev`,`other_data`) VALUES ('AZ','foo bar');
> OK
SELECT LAST_INSERT_ID();
> "3"
// we have the ID, we're done
插入一行将被忽略:
INSERT IGNORE INTO `states` (`abbrev`,`other_data`) VALUES ('AK','duplicate!');
> OK
SELECT LAST_INSERT_ID();
> "0"
// oops, it already exists!
SELECT id FROM `states` WHERE `abbrev` = 'AK'; // our UNIQUE constraint here
> "2"
// there we go!
或者,有一种可能的解决方法可以一步完成此操作 - 使用 REPLACE INTO
而不是 INSERT IGNORE INTO
- the syntax is very similar .但是请注意,这种方法有副作用 - 这些对您来说可能重要也可能不重要:
- REPLACE 删除+重新创建行
- 所以 DELETE 触发器被触发了,嗯,被触发了
- 此外,即使该行存在,主 ID 也会递增
INSERT IGNORE
保留旧行数据,REPLACE
用新行数据替换它
关于mysql - 插入后忽略获取主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6291405/