How to achieve unique auto-incremented id for rows across multiple tables?

荒凉一梦 提交于 2019-12-10 23:19:40

问题


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

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