Auto incrementing a non-unique id upon creation using SQLAlchemy

限于喜欢 提交于 2019-12-06 01:04:10
Sylvain Leroux

To quote a classic MySQL error message:

there can be only one auto column and it must be defined as a key:

auto_increment column must be either (in) the primary key or (in) a key (also known as index in MySQL, which may or may be unique).


As for:

SELECT MAX(id) FROM tbl INTO @new_id;
INSERT INTO tbl (id, ...) VALUES (@new_id, ....);

You clearly understand that if two concurrent requests do the same thing, you will end up having two new rows, totally unrelated, with the same ID. An you probably don't want to use table locks to avoid that pitfall.

As of myself, I would say "don't do that". Maybe that would make some things more easy in your application, but I bet that would made tons of other things far more complicated or much less robust.


But ... if the real problem if to keep the "post id" constant, remember that auto_increment could be part of a key (http://sqlfiddle.com/#!2/9b4b45/1):

create table tbl(id int auto_increment not null, 
                 rev int not null default 1,
                 content TEXT,
                 primary key(id,rev));

-- insert 3 new contents with "auto id" and default revision 1
insert into tbl (content) values ("alpha"), ("bta"), ("gamma");

Say there is an error in the item id2,rev1. You could insert a new revision:

insert into tbl (id, rev, content) values (2,2,"beta");

If you want to see the various revision of item id2:

select * from tbl where id=2 order by rev;

You will have to find how to do that with SQLAlchemy (:D), but this is definitively possible with MySQL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!