开发者

mysql random rows

开发者 https://www.devze.com 2022-12-14 11:20 出处:网络
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

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 alphabe开发者_JS百科t='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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消