shuffle random MYSQL results

前端 未结 4 454
广开言路
广开言路 2020-12-11 05:27

The following code displays random database images as well as one specific image (which is what I want). How can I shuffle these results after database query as image ID 11

4条回答
  •  孤街浪徒
    2020-12-11 06:25

    1. First select the specific image then union other 6 images collected by random.
    2. When you sort something by rand() all the rows get unique random value to sort so the subgroups aren't sorted. So using more columns in order by clause does not work if there is rand() present. Hence I have used alias the result and sort it again.

    See the query

    (SELECT * 
     FROM   `profile_images` 
     WHERE  id = 11 
     LIMIT  1) 
    UNION 
    (SELECT * 
     FROM   (SELECT * 
             FROM   `profile_images` 
             WHERE  id != 11 
             ORDER  BY Rand() 
             LIMIT  6) `t` 
     ORDER  BY id DESC) 
    

提交回复
热议问题