Basically I would like to do the following in one single query. Is it possible?
$q = mysql_query('select * from table ORDER BY rand() LIMIT 5');
$s;
while($r = mysq_fetch_array($q)){
$s[i] = $r['id'];
// Do stuff
}
$u = mysql_query("update t开发者_运维技巧able SET lastUpdated = NOW() where id in (".implode(',',$s).")");
You can just add
ORDER BY RAND() LIMIT 5
To the end of your update query
EDIT:
I missed part of the question at first. The above will work if you just need to update 5 random rows. However, it looks like you need to get 5 random IDs from your table, perform some action with those IDs, and update those rows. Unfortunately, UPDATE queries can modify data, and SELECT queries can retrieve data, but neither query can do both. You could probably create some sort of stored procedure to update / select 5 random rows, but that would be more complicated than the 2 queries you currently have
EDIT #2:
If your reason for wanting to do this in the same query is concurrency, you could check out MySQL's Locking Read feature.
You can't use select/update statements for the same table in the same query.
精彩评论