[英]MySQL sort by, then sort a selection by
我通過查詢從數據庫中提取了許多行。 假設結果是120行。 我想按“分數”排序這些行。 這很容易,因為每一行都有一個名為“得分”的字段。 接下來,我想對結果的前20行進行隨機排序。 因此:按分數第1階,然后隨機第20階。 我該怎么做?
編輯:要清楚:我想顯示所有120行,就在隨機數的前20行之后。
謝謝!
假設您使用類似以下SQL的代碼將所有結果存儲在PHP數組$rows
:
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);
您是否嘗試過改組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
這是僅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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.