views:

96

answers:

2

how to form a query to select 'm' rows randomly from a query result which has 'n' rows.

for ex; 5 rows from a query result which has 50 rows

i try like as follows but it errors

 select * from (select * from emp where alphabet='A' order by sal desc) order by rand() limit 5;

u can wonder that why he needs sub query, i need 5 different names from a set of top 50 resulted by inner query.

+1  A: 
SELECT * FROM t
ORDER BY RAND() LIMIT 5

or from your query result:

SELECT * FROM ( SELECT * FROM t WHERE x=y ) tt
ORDER BY RAND() LIMIT 5
Peter Lang
2nd query result error as follows :ERROR 1248 (42000): Every derived table must have its own alias
Paniyar
just add 'some_name' (without the quotes) after the closing parenthese
streetpc
note that `order by rand()` becomes expensive when the number of rows becomes large
streetpc
Thanks, I added the alias
Peter Lang
+1  A: 

This will give you the number to use as 'm' (limit)

TRUNCATE((RAND()*50),0);

...substitute 50 with n.
To check it try the following:

SELECT TRUNCATE((RAND()*50),0);

I should warn that this could return 0 as a result, is this ok for you?

For example you could do something like this:

SELECT COUNT(*) FROM YOUR_TABLE

...and store the result in a variable named totalRows for example. Then you could do:

SELECT * FROM YOUR_TABLE LIMIT TRUNCATE((RAND()*?),0);

where you substitute the '?' with the totalRows variable, according to the tech stack you are using.
Is it clearer now? If not please add more information to your question.

Alberto Zaccagni
sorry i couldn't understand your solution .can u tell me more please
Paniyar
Edited, see if it's clearer
Alberto Zaccagni