By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,871 Members | 2,444 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,871 IT Pros & Developers. It's quick & easy.

Getting random row from MySQL

100+
P: 144
Hi, i'm learning php and MySQL

and i want to display only let's say 4 records (different/random every page load) from my query that could be more than 4. but no repeating records would be shown.

i could think a way that's kinda hard. is there any function in php or mysql that can make it easier?

thx
Dec 26 '07 #1
Share this Question
Share on Google+
2 Replies


Atli
Expert 5K+
P: 5,058
Hi.

A very simple way to do this would be to simply use a query like:
Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM tbl ORDER BY RAND() LIMIT 4
  2.  
But this will get slow on large tables.

Another way would be to find the highest possible ID in your table, select a few random numbers and fetch only those rows.

Keep in mind that this will not be truly random if there are gaps in the ID's in your table, but I doubt that will have any notable effect.
Dec 26 '07 #2

100+
P: 144
hi, thx Atli

i'll try this one.

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM tbl ORDER BY RAND() LIMIT 4
  2.  
Dec 26 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.