简体   繁体   中英

update a random row from a table

I've got this code here:

    UPDATE starinformation SET starOwner = -1 WHERE (
SELECT starinformation.starID
ORDER BY RAND( ) 
LIMIT 1
)

I want to update a random row from a table with information pulled from that table and only effect 1 row.

There are a lot of problems with this approach:

  • MySQL does not allow combining a modifying outer query with a selecting subquery to touch the same table
  • ORDER BY RAND() LIMIT 1 is a major performance killer: It will create an intermediate result of ALL rows - ie if your table contains 1 megarows, you will touch every single one of them.

My recommendation is to

  • allways have a sortable single-field PK
  • Run SELECT ROUND(RAND()*COUNT(*)) AS num FROM starinformation , returning $num
  • Run UPDATE starinformation SET starOwner = -1 ORDER BY [pk-field] LIMIT $num,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