简体   繁体   中英

How can I use multiple columns of SELECT into UPDATE statement?

I have a query like this:

UPDATE t1 
SET t1.col1 = ( SELECT col1 FROM t2 WHERE <some_complex_conditions> ),
    t1.col2 = ( SELECT col2 FROM t2 WHERE <some_complex_conditions> )
WHERE id = :id;

As you see, I have to execute the same query twice, every time for one column. Also as I've mentioned, that SELECT query has some complex conditions which need lots of processing. Now I want to know, how can I handle the UPDATE statement to get the update those two columns by single SELECT statement?

Something like this:

SELECT col1, col2 FROM t2 WHERE <some_complex_conditions> 

In other word, how can I use this ^ into the UPDATE statement?

请参阅手册stackoverflow中的多表语法

It's possible to update joined table. I think that it should be possible to join select statement, but I'm not sure, but I think example below shows equivalent query:

UPDATE t1
LEFT JOIN t2
 -- joining condition, there can be the part <some complex condition>
 ON t1.id = t2.ref_id AND t2.col3 = 'whatever you want'
SET t1.col1 = t2.col1, t1.col2 = t2.col2
--additional condition like WHERE t2.col1 IS NOT NULL

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