How do I randomly display categories in a particular order

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
adsegzy
Forum Contributor
Posts: 184
Joined: Tue Jul 28, 2009 9:26 am

How do I randomly display categories in a particular order

Post by adsegzy »

Hello there,

I have an online store,where the members can subscribe to any of the 3 packages (1, 2 & 3). Below is a sample of the Products DB table.


id package product status
1 3 Biro 1
2 1 Paper 1
3 3 Pin 0
4 2 Eraser 1
5 2 Blade 1
6 3 Bag 1
7 2 Pen 0
8 1 Sharpener 1
9 1 Shoe 1
10 2 Chair 1

I displayed the package 3 products first, then package 2 products next then package 1 products last like this;

Code: Select all

$get_products = mysql_query("SELECT * FROM products WHERE status='1' ORDER BY package DESC");
But what i want to really do is to randomly display all package 3 products first, then randomly display package 2 products and lastly display package 1 products randomly. So that no particular item will always be at the top while some will always be on the bottom.

How do I write the syntax. Thanks in advance
User avatar
Celauran
Moderator
Posts: 6425
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How do I randomly display categories in a particular ord

Post by Celauran »

You could add RAND() to your select and then sort by that
User avatar
Celauran
Moderator
Posts: 6425
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How do I randomly display categories in a particular ord

Post by Celauran »

Code: Select all

SELECT *, RAND() AS shuffle
FROM products
WHERE status='1'
ORDER BY package DESC, shuffle
Post Reply