MySQL ORDER BY rand(), name ASC

前端 未结 5 628
甜味超标
甜味超标 2020-12-02 18:09

I would like to take a database of say, 1000 users and select 20 random ones (ORDER BY rand(),LIMIT 20) then order the resulting set by the names.

5条回答
  •  Happy的楠姐
    2020-12-02 19:00

    Instead of using a subquery, you could use two separate queries, one to get the number of rows and the other to select the random rows.

    SELECT COUNT(id) FROM users; #id is the primary key
    

    Then, get a random twenty rows.

    $start_row = mt_rand(0, $total_rows - 20);
    

    The final query:

    SELECT * FROM users ORDER BY name ASC LIMIT $start_row, 20;
    

提交回复
热议问题