MySQL ORDER BY rand(), name ASC

前端 未结 5 618
甜味超标
甜味超标 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条回答
  •  独厮守ぢ
    2020-12-02 18:52

    Use a subquery:

    SELECT * FROM (
        SELECT * FROM users ORDER BY RAND() LIMIT 20
    ) u
    ORDER BY name
    

    or a join to itself:

    SELECT * FROM users u1
    INNER JOIN (
        SELECT id FROM users ORDER BY RAND() LIMIT 20
    ) u2 USING(id)
    ORDER BY u1.name
    

提交回复
热议问题