简体   繁体   中英

Is there a way to add multiple values with same ID in two different tables?

Using PHP and mySQL, I need to add multiple values in 2 mysql tables: the first table would have the more important informations and the second one would have the less important informations about each items.

To be more clear, ONE element would have his informations split in two tables.

(I need this for some reasons but two of them are: having the first table the less weight possible, and the second table would store datas that will be erase after a short time (meanwhile the first table keeps all the datas it stored).)

In the best scenario, I'd like to add a row in each table about one item/element with the same id in each table. Something like this:

Table 1 id|data_1_a|data_1_b|...

Table 2 id|data_2_a|data_2_b|...

So if I add an element which get the ID "12345" in the table 1, it adds the datas in the table 2 with the same ID "12345".

To achieve this, I think of two solutions:

  1. Create the ID myself for each element (instead of having an auto_increment on table 1). The con is that it would probably be better to check if the ID doesn't already exist in the tables everytime I generate an ID...
  2. Add the element on table 1, get its ID with $db->lastInsertId(); and use it to add the element's datas on table 2. The con is that I have to add one element by one element to get all the IDs, while most of the time I want to add a lot of elements (like one, two or three hundreds !) at once

Maybe there's a better way to achieve this?

lastInsertId() reports the first value generated by the last INSERT statement executed. It's reliable to assume that when you insert many rows, they are given consecutive id values following that first value. For example, the MySQL JDBC driver relies on this assumption, so it can report the set of id values generated.

This assumption breaks only if you deliberately set innodb_autoinc_lock_mode=2 (interleaved). See https://dev.mysql.com/doc/refman/8.0/en/innodb-auto-increment-handling.html for details about that.

But if it were my task, I would still choose to use a single table. When you find you don't need some of the columns anymore, use UPDATE to set them to NULL. This will eliminate the problems you're facing with assuring the same id is used across two tables.

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