I extract a number of rows from my DB with a query. Let's say that the result is 120 rows. I want to order these rows by 'score'. That's easy, since every row has a field called 'score'. Next I want to order the first 20 rows of the result randomly. So: 1st order by score, then order first 20 randomly. How would I do this?
EDIT: to be clear: I want to show ALL 120 rows, just onder the first 20 of them randomly.
Thanks!
Let's suppose you've got all your results in a PHP array $rows
, using something like this SQL:
SELECT * from `table_name` order by `score`;
It sounds like you know how to do that bit, so I omit the details. The bit you want is the following:
// Get the first 20 rows
$top_twenty = array_slice($rows, 0, 20)
// Order them randomly
shuffle($top_twenty);
// Put them back into the $rows array, with their new order
$rows = array_replace($rows, $top_twenty);
Have you tried shuffling the associative array obtained in the result of the SQL?
$stmt = $db->query("SELECT * FROM table ORDER BY score LIMIT 20");
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
shuffle($array);
foreach($array as $item) {
// Do something
}
SET @rowNum=0;
SELECT @rowNum:=@rowNum+1 AS rowSeq,t.*
FROM tableName t
ORDER BY case WHEN rowSeq < 20 THEN Rand() ELSE score END
Here is a SQL-only (well MySQL-only) solution:
SELECT *
FROM (SELECT *, @rn := @rn + 1 as rn
FROM table cross join
(select @rn := 0) const
ORDER BY score
) t
ORDER BY (rn <= 20) desc,
(case when rn <= 20 then rand() end),
score;
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.