简体   繁体   中英

How do I update the values of a column in a database using another mapping table? (MySQL)

Imagine I have the following tables

Table 1

id     question_id  tag_id
1           1         10
2           5          8

Table 2 (Mapping table)

old_tag_id   new_tag_id
   8             89
   9             90
   10            91

Result That I'm trying to achieve:

Table 1

id    question_id   tag_id
1          1          91
2          5          89

. .

(that is, Update the whole table in using a single query, since I have a table consisting of millions of rows)

I tried using subqueries in SQL but I can't seem to handle when the subqueries seem to return more than one row.

Thanks In Advance

update table1 t1
join mapping_table t2 on t1.tag_id = t2.old_tag_id
set t1.tag_id = t2.new_tag_id

You can use an INNER JOIN query

UPDATE table1 a
INNER JOIN table2 b
ON a.tag_id = b.old_tag_id
SET a.tag_id = b.new_tag_id

Can you try the below query.

UPDATE Table1 t1 
SET t1.tag_id = (SELECT t2.new_tag_id 
              FROM Table2 t2
              WHERE t1.tag_id = t2.old_tag_id)

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