问题
I've got several tables in a database, let's say they're called table1, table 2, etc. All tables have a primary key column 'id' with auto-increment.
In my current configuration it happens that when inserting into table1, the generated id is 1. Afterwards when inserting into table2, the generated id happens to be 1 as well.
How to force absolutely unique ids across all tables in a database? I want when inserting into table1, generated id to be 1, and if afterwards inserting into table2, generated id be 2?
I used mysql server on some machine and did not have this problem, but when I installed mysql on my local machine, it started to occur. So I guess it must be some kind of a setting that is applied to the mysql configuration?
Thank you
回答1:
you can use UUID.
INSERT INTO mytable(id, name) VALUES(SELECT UUID(), 'some data');
Read more about UUID: http://mysqlbackupnet.codeplex.com/wikipage?title=Using%20MySQL%20With%20GUID%20or%20UUID
回答2:
You can create SEQUENCE which can be used globally.
CREATE SEQUENCE serial
INCREMENT 1
MINVALUE 0
MAXVALUE 200
START 364
CACHE 1;
Edit: Sequences are supported in Postgres but this can be achieved in MySql by setting value for AUTO_INCREMENT and one can use LAST_INSERT_ID(). link
来源:https://stackoverflow.com/questions/16336850/how-to-achieve-unique-auto-incremented-id-for-rows-across-multiple-tables