简体   繁体   中英

Update two columns in MySQL from select statement

I'm trying to update two columns in MySQL:

update table1
set (table1.score, table1.count) = 
(select (table2.maxScore - table2.score ) as diff, count(*)
from table2
where (table2.maxScore - table2.score) <= 600
and table2.age > 50
group by diff);

But, MySQL does not support this syntax. I've seen some examples using JOIN, but I can't make it work here. Many thanks for any help!

Maybe you should SET their values separately,

UPDATE scoresUniverse 
SET scoreUniver.GNfemScore = (Analytics.GN_recency_max_score - Analytics.GN_recency_score ),
ScoresUniverse.GNfemCount = (Select count(*) from Analytics.GN_recency_score where (Analytics.PR_recency_max_score - Analytics.PR_recency_score) <= 600 and Analytics.Older_female_50 > 0)

I figured it out! MySQL can definitely update more than one column at once. I needed to change my original query because MySQL requires using JOIN with ON when updating more than one column. To prove it, I added an extra column "secondCol" to my example. I have looked all over the web for this, and never found the answer. I hope this helps some people.

 update table1 join
 (select (table2.maxScore - table2.score ) as diff, count(*) as count
 from table2
 where (table2.maxScore - table2.score) <= 600
 and table2.age > 50
 group by diff) as scores
 on table1.count = scores.count
 set table1.score = scores.diff, table1.secondCol = scores.count;

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