shuffle random MYSQL results

前端 未结 4 423
广开言路
广开言路 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:08

    You can shuffle them after they are retrieved to php.

    $photos = array();
    while ($get_photo = mysql_fetch_array($photo))
        $photos[] = $get_photo;
    
    shuffle($photos);
    

    Or you can do it with subqueries:

    SELECT A.* FROM (
        SELECT * FROM `profile_images` 
        ORDER BY (ID = 11) DESC, RAND()      
        LIMIT 7
    ) as A
    ORDER BY RAND()
    
    0 讨论(0)
  • 2020-12-11 06:21

    First select the image with ID 11 and than query the rest with UNION keyword

    SELECT *
    FROM Images
    Where ID = 11
    UNION
    SELECT *
    FROM Images
    WHERE ID != 11
    
    0 讨论(0)
  • 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) 
    
    0 讨论(0)
  • 2020-12-11 06:27

    Its doesnt need to be that complicated if you just put for example

    SELECT * FROM tbl_table ORDER BY RAND()
    

    This will randomise your data. if you want to limit out how many images you show then just put:

    SELECT * FROM tbl_table ORDER BY RAND() LIMIT 6
    
    0 讨论(0)
提交回复
热议问题