我正在尝试在MySQL中生成序列表,以便可以从获得唯一ID last_insert_id。
last_insert_id
问题是我需要动态地多个序列。
首先,我创建了一个表:
CREATE TABLE `sequence` ( `label` char(30) CHARACTER SET latin1 NOT NULL, `id` mediumint(9) NOT NULL DEFAULT '0', PRIMARY KEY (`label`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8
然后尝试使用http://dev.mysql.com/doc/refman/5.0/en/information- functions.html#function_last-insert- id中的示例获取编号
UPDATE sequence SET id = LAST_INSERT_ID(id + 1) WHERE label = 'test'; SELECT LAST_INSERT_ID();
一段时间后,我意识到我还需要安全地为新标签生成行。因此,我将此架构更改为:
CREATE TABLE `sequence` ( `label` char(30) CHARACTER SET latin1 NOT NULL, `id` mediumint(9) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`label`,`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8
我只是放弃了using WHERE子句来更新其ID。
WHERE
INSERT INTO sequence (label) values ( ? ) SELECT LAST_INSERT_ID()
这是正确的方法吗?我想知道是否有更好的解决方案。
MyISAM引擎将为您做到这一点-
表定义:
CREATE TABLE `sequence` ( `label` char(30) CHARACTER SET latin1 NOT NULL, `id` mediumint(9) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`label`,`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
填充表:
INSERT INTO sequence VALUES ('a', NULL); -- add some 'a' labels INSERT INTO sequence VALUES ('a', NULL); INSERT INTO sequence VALUES ('a', NULL); INSERT INTO sequence VALUES ('b', NULL); -- add another labels 'b' INSERT INTO sequence VALUES ('b', NULL); INSERT INTO sequence VALUES ('a', NULL); -- add some 'a' labels INSERT INTO sequence VALUES ('a', NULL);
显示结果:
SELECT * FROM sequence; +-------+----+ | label | id | +-------+----+ | a | 1 | | a | 2 | | a | 3 | | a | 4 | | a | 5 | | a | 6 | | b | 1 | | b | 2 | +-------+----+