INSERT重复键

时间:2017-04-26 21:10:09

标签: mysql sql-insert auto-increment myisam last-insert-id

我有一个mySQL 5.7 myISAM 表T:

Col  Key    Other
A    PRI   
B           autoincrement
C

我想执行以下操作: 给定值x和y

  • 如果已经有一行A = x,请给我回B
  • 否则,在A = x和C = y处插入一行,并给我回B

最简单的方法似乎是

SELECT B FROM T WHERE A=x;
if the row doesn't exist,
INSERT INTO T SET A=x, C=y;
SELECT LAST_INSERT_ID();

但是,这是非原子的,这意味着我需要实现某种锁定。

我希望我能用

INSERT IGNORE INTO T SET A=x, C=y;
SELECT LAST_INSERT_ID();

但是当重复键上的INSERT被忽略时,LAST_INSERT_ID()不会返回B.

有没有一种简单的方法可以原子地完成这个,而不需要锁定?

3 个答案:

答案 0 :(得分:1)

请参阅IODKU的class Pet(object): def __init__(self, name, animal_type, age): self.__name = name self.__animal_type = animal_type self.__age = age def set_name(self, name): self.__name = name def set_type(self, animal_type): self.__animal_type = animal_type def set_age(self, age): self.__age = age def get_name(self): return self.__name def get_animal_type(self): return self.__animal_type def get__age(self): return self.__age def main(): name = input('What is the name of the pet: ') animal_type = input('What type of pet is it: ') age = int(input('How old is your pet: ')) pets = Pet(name, animal_type, age) print('This will be added to the records.') print('Here is the data you entered: ') print('Pet Name: ', pets.get_name()) print('Animal Type: ', pets.get_animal_type()) print('Age: ', pets.get__age()) main() 部分中如何使用id=LAST_INSERT_ID(id)的示例。 https://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html

答案 1 :(得分:0)

我认为没有办法用LAST_INSERT_ID()来实现,因为只有在实际插入某些内容并分配了新ID时才会设置。{p>}您必须选择刚插入的密钥:

INSERT IGNORE INTO T SET a=x, C=y;
SELECT B FROM T WHERE a = x;

答案 2 :(得分:-1)

select max(id) from T

这是表格的最后一个ID