Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

sql - Update multiple rows by joining many tables

I have 3 tables, i'm trying to find a way to update multiple rows using other tables data. Update only null or empty "info" column in table1 with "data" column in the Table2 by checking if the id in table1 is linked to the idTab1 in table3 and the id in table2 is linking to idTab2 in Table3

enter code here
Table1
id, info
 --------
 1, null
 2, info2
 3, null
 
 Table2
 id, data
  ---------
  1, info1
  2, info2
  3, info4

 Table3
 idTab1, idTab2
 ------
 1, 1
 2, 2
 3, 3

The desired result is :

Table1
id, info
--------
 1, info1
 2, info2
 3, info3

Thank you in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can join the 3 tables in the UPDATE statement with this syntax:

UPDATE Table1
SET Table1.info = t2.data
FROM Table3 t3 INNER JOIN Table2 t2
ON t2.id = t3.idTab2
WHERE t3.idTab1 = Table1.id AND Table1.info IS NULL

See the demo.
Results:

> ID |  INFO
> -: | ----:
>  1 | info1
>  2 | info2
>  3 | info4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...