简体   繁体   中英

Cross reference between two tables

I have two mysql tables with the same structure and with records that are changed over time and that now I need to compare. Tables are T1 and T2 and both have the columns:

Id,
Name,
Id2.

I have stored in T1.Id2 the reference id of the matching records (by Name ) of the second table. So, for example, in T1 I have the following value:

id  name      id2
---------------------
1   mario     0   
2   vittorio  0
3   andrea    2
4   giuseppe  3

and need to have the following results in T2:

id  name      id2
--------------------
 1  riccardo   0
 2  andrea     3
 3  giuseppe   4
 5  giacomo    0

So, I need to store in the second table, the id of the first table for the same records. Where in T1 there is T1.Id2>0 i need to set in T2.Id2 the corresponding T1.id Any ideas for a query?

Try an update join:

UPDATE table2 t2
INNER JOIN table1 t1
    ON t1.id2 = t2.id
SET t2.Id2 = t1.id
WHERE
    t1.Id2 > 0;

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