简体   繁体   中英

MySQL having 1 primary key with auto increment for 2 tables

I have 2 tables ' table1 ' & ' table2 ', both have column named ' id ' ( primary key ) and both have auto increment. The problem is how do I make the primary key viable for the both tables.

Example: I enter id ' 100 ' in ' table1 ' and after that if I try to enter a new record in ' table2 ' I would have ' 101 ' in ' table2 '

I thought 'foreign key' would do the job but it did the exactly opposite of what I need

Strictly speaking, there's no way to do what you describe without resorting to extra queries or extra locking.

You can simulate it by creating a third table, into which you insert to generate new id's, then use LAST_INSERT_ID() to insert into either table1 or table2. See example in How to have Unique IDs across two or more tables in MySQL?

Also see some discussion of this problem and solutions here at the popular MySQL Performance Blog: Sharing an auto_increment value across multiple MySQL tables

But I agree with the comment from @Barmar, this might be an indication of a bad design for a database. If you have a requirement to make the auto-increment PK unique across multiple tables, this may mean that the two tables should really be one table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM