首页 > 代码库 > Mysql insert without auto-increase when duplicate

Mysql insert without auto-increase when duplicate

INSERT INTO video_tag_all(tagname,ctime)      SELECT 利物浦,1413954816 FROM video_tag_all      WHERE (SELECT last_insert_id(id) FROM video_tag_all WHERE tagname=利物浦) IS NULLLIMIT 1;SELECT LAST_INSERT_ID();

背景:使用insert ignore或insert ... on duplicate key update,都会使自增字段加1,造成不必要的数据空洞,上面的SQL避免了该问题并能够在任何时候都拿到记录ID

缺陷:必须保证表初始化时有一条记录,否则select .... limit 1查不出数据来,就无法insert

Mysql insert without auto-increase when duplicate