Board index   FAQ   Search  
Register  Login
Board index php forum :: Database mySQL & php coding

Select a range of Records from Table

Codes here !

Moderators: macek, egami, gesf

Select a range of Records from Table

Postby shnkrsv » Fri Jul 20, 2012 2:20 am

Hai Friends,

Am trying to display a range of records from my table.

Am using the code
Code: Select all
$find = "SELECT * FROM $category1 ORDER BY RAND() LIMIT 4";


This works gread, which displays the random of records and limited to 4 to display.

But what i exactly need is to display only 4 records from only top 10 rows of the table in random.

I have tried, this
Code: Select all
$find = "SELECT * FROM $category1 ORDER BY RAND() LIMIT 4,10";


But this will display the range between 4 to 10 records, so it will display 6 records, but i need only 4 records from that 6, but within the top 10.

Please give me suggestion,

Thanks and Regards,

Sivasankar Ramalingam.
User avatar
shnkrsv
New php-forum User
New php-forum User
 
Posts: 27
Joined: Sun Oct 30, 2011 10:48 pm
Location: Coimbatore

Re: Select a range of Records from Table

Postby Nullsig » Fri Jul 20, 2012 3:26 am

First off your second query won't work because you aren't grabbing the top 10 items and then randomizing them and grabbing 4. You are instead grabbing the top 10 randomized items and then grabbing 4th-10th ranked results.

If you are fine with the latter than your case than your original query is statistically correct. Grabbing any 4 records from the result set will give you statistically the same results.


If you instead need to order these specifically and then grab 4 of the top 10 results at random you need to do the following.


You can do this a two, and possibly more, different ways.

First way is to query for the first 10 rows and then use a randomized array in PHP to pull for records from the result set while iterating through.

The second way involves nesting queryies:
Code: Select all
SELECT *
FROM (SELECT *
          FROM $category1
          ORDER BY <what ever prioritizes these records>
          LIMIT 10) x
ORDER BY RAND()
LIMIT 4
User avatar
Nullsig
php-forum Fan User
php-forum Fan User
 
Posts: 981
Joined: Thu Feb 17, 2011 6:52 am
Location: Racine, WI

Re: Select a range of Records from Table

Postby shnkrsv » Sat Jul 21, 2012 2:05 am

Thank you Nullsig... :) :) its really works... thank you very much... :D
User avatar
shnkrsv
New php-forum User
New php-forum User
 
Posts: 27
Joined: Sun Oct 30, 2011 10:48 pm
Location: Coimbatore


Return to mySQL & php coding

Who is online

Users browsing this forum: Yahoo [Bot] and 2 guests

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.