简体   繁体   中英

How to combine SELECT and UPDATE MySQL

I'm aggregating data and in a table and basically moving the data from one table to the next.

Currently, I'm selecting all the data from MySQL and then inserting it back into the new table.

Is there a way to combine this query to do it all within MySQL rather than taking the data out and then back in?

Basically, I want to combine the following:

'''update landing_pages_v3 set mobile_first_place_rankings=%s where id=%s''', data

'''select count(keyword), lp_id from keywords_v3 where profile_id=%s and device=%s and positions=1 group by lp_id''', (profile_id, device)

You can JOIN the the query as a subquery in the UPDATE :

UPDATE landing_pages_v3 AS l
JOIN (
    SELECT count(*) AS ct, lp_id
    FROM keywords_v3
    WHERE profile_id=%s AND device=%s AND positions=1
    GROUP BY lp_id
) AS k ON l.id = k.lp_id
SET mobile_first_place_rankings = k.ct

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