Riunix's Blog
Select random data (mysql)
Sometimes, we need random data for showing in our home page, example : random product, random photo, etc. To get random data, we can just put a simple script to our mysql query.
Just use "rand()" funtion. Here the example :
First, we create new database and table for this sample.
For example, we need 5 random member for show in our home page, so we can use this query
We use 'limit 5' because we want limit the result just 5 random data. Every time you execute this query, the result will be different.
Just use "rand()" funtion. Here the example :
First, we create new database and table for this sample.
| create database `db_test`; use `db_test`; CREATE TABLE `member` ( `id` int(11) NOT NULL auto_increment, `name` varchar(100) default NULL, `location` varchar(100) default NULL, PRIMARY KEY (`id`) ); insert into `member`(`id`,`name`,`location`) values (1,'Jerry','New York'),(2,'Anastasya','Sydney'),(3,'Rudy','Hawai'),(4,'Sonoko','Tokyo'),(5,'Fredy','Singapore'),(6,'Anne ','Beijing'),(7,'Hannah','Silicon Valley'),(8,'Derick','Singapore'),(9,'Johan','Jakarta'),(10,'Teo','Seoul'); |
For example, we need 5 random member for show in our home page, so we can use this query
| select * from member order by rand() limit 5; |
We use 'limit 5' because we want limit the result just 5 random data. Every time you execute this query, the result will be different.
Comments for "Select random data (mysql)"
Anton Ongsono
08.October.2009 05:08:24 PM
order by rand() is not recommended even you limit 1; because it will random all your data first. to avoid it better use where id in(rand_no1,rand_no2)
anton..thx for the advice. Yup, you're right , it's not recommended if the data in our database is big, but if the data in our database not very big, why not we use it :D (
It will shorten our code => just for lazy programmer like me :P ).
ow thx for this great tutorial too :p
