Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shuffle random MYSQL results

Tags:

php

mysql

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 is always displayed first? I want image ID 11 displayed randomly amongst the others.

Can I use SHUFFLE(). If so where exactly do I put it as at the moment?

Any help would be appreciated as still learning PHP

Thanks.

<?php 

mysql_connect("", "", "") or die(mysql_error()) ; 
mysql_select_db("images") or die(mysql_error()) ;


$photo=mysql_query("SELECT * FROM `profile_images` ORDER BY (ID = 11) DESC, RAND()      
LIMIT 7");


while($get_photo=mysql_fetch_array($photo)){ ?>

<div style="width:300px;">


<img src="<? echo $get_photo['url']; ?>">


</div>

<? } ?>
like image 619
user1022772 Avatar asked Feb 26 '12 20:02

user1022772


4 Answers

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()
like image 128
gintas Avatar answered Oct 06 '22 04:10

gintas


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
like image 37
MattClaff Avatar answered Oct 06 '22 04:10

MattClaff


  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) 
like image 37
Shiplu Mokaddim Avatar answered Oct 06 '22 05:10

Shiplu Mokaddim


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
like image 21
Peter Kiss Avatar answered Oct 06 '22 05:10

Peter Kiss