我通过查询从数据库中提取了许多行。让我们说结果是120行。我想通过“得分”排序这些行。这很容易,因为每一行都有一个名为“得分”的字段。接下来我想随机排序结果的前20行。所以:按分数排序,然后先随机排序20。我该怎么做?
编辑:要清楚:我想显示所有120行,只是随机地显示前20行。
谢谢!
答案 0 :(得分:4)
假设您已经在PHP数组$rows
中获得了所有结果,使用类似SQL的内容:
SELECT * from `table_name` order by `score`;
听起来你知道该怎么做,所以我省略了细节。你想要的是以下几点:
// 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);
答案 1 :(得分:1)
您是否试过改组在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
}
答案 2 :(得分:1)
SET @rowNum=0;
SELECT @rowNum:=@rowNum+1 AS rowSeq,t.*
FROM tableName t
ORDER BY case WHEN rowSeq < 20 THEN Rand() ELSE score END
答案 3 :(得分:0)
这是一个仅限SQL(仅限MySQL)的解决方案:
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;