简体   繁体   中英

MySQL odd and even auto-incremented IDs

I have two tables in MySQL . Both tables store exactly the same thing, only that one table stores data that is not final (will be later changed) and one table stores final data.

NotFinal Table
----------------------
ID ParentID  Value
1     2       0.5
2     2       0.3

.

Final Table
----------------------
ID ParentID  Value
1     1       0.5
2     2       0.3
3     2       0.4

Now, the thing is that I want to select the ID of all entires that have ParentID = 2 , doesn't matter from which table. If I select from their join then I will get 1,2,2,3 in which case the ID 2 is duplicate (ID 2 has ParentID 2 in both first and second table).

So, the actual problem is I don't know from which table the ID came from . To fix this problem I was thinking in Non-final table to only have odd IDs and in the final table to have only even IDs. Doing this will never result in conflicting IDs and I will always know which ID came from which table.

Can I set up MySQL auto-increment so that the IDs in the first table are odd and in the second one are even?

So the tables would look like this:

NotFinal Table
----------------------
ID ParentID  Value
1     2       0.5
3     2       0.3

.

Final Table
----------------------
ID ParentID  Value
2     1       0.5
4     2       0.3
6     2       0.4

You can use configuration options auto_increment_increment and auto_increment_offset as mentioned in the MySQL manual .

Their primary use is for replication, but as they can be changed also in each session, you can use them for your purpose. Just set them as you need before manipulating either of these 2 tables (change only the session variables, not global ones).

I don't know from which table the ID came from

You can add details into your result set independently for each table in your union select. eg add a column for is_final :

SELECT ID,ParentID,Value, true as `is_final` FROM `Final`
union
SELECT ID,ParentID,Value, false as `is_final` FROM `NotFinal`

Why not have them both in the SAME table? Add an extra integer column named IS_FINAL which can be set to 1 or 0. Set it to 0 for non-final records and 1 for final records. This would be a much cleaner way of solving the problem.

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