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.
精彩评论