简体   繁体   中英

SQL SELECT then UPDATE in one query

I have to randomly select a row from a MySQL DataBase, then increment by one a counter on that row (same table). At the moment, I'm running

SELECT id, img, title, alt, ... FROM table WHERE ... ORDER BY RAND() LIMIT 1

and then separately

UPDATE table SET counter = counter + 1 WHERE id = $id

Thus running two queries. Is there a way to do this all in one query? Thanks!

If you only need to increment the value and not bring back a row to process you could do the following:-

UPDATE fred
INNER JOIN
(
    SELECT id
    FROM fred
    ORDER BY RAND()
    LIMIT 1
) sub0
ON fred.id = sub0.id
SET fred.counter = fred.counter + 1

Or simpler:-

UPDATE fred
SET fred.counter = fred.counter + 1
ORDER BY RAND()
LIMIT 1

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