开发者

How can I fetch rand records from a union query?

SELECT a, b, c FROM ".TBL_A." WHERE [statement] **`ORDER BY RAND()`** LIMIT 1
UNION
(SELECT a, b, c FROM ".TBL_A." WHERE [different statement] ORDER BY RAND() LIMIT 5)";

This query works fine without first ORDER BY RAND(), but what I need is to fetch first rec randomly by first statement and then 5 other random recs by other statement.

It seems that I can't use two order by statements on one query...

Any开发者_如何学Go thoughts?


Your approach should work. Perhaps you just need to wrap your selects in an outer select.

SELECT * FROM (
    SELECT a, b, c FROM your_table WHERE [statement] ORDER BY RAND() LIMIT 1
) T1
UNION
SELECT * FROM (
    SELECT a, b, c FROM your_table WHERE [different statement] ORDER BY RAND() LIMIT 5
) T2

Note. Make sure that you have considered the difference between UNION and UNION ALL. It is a common mistake to get them mixed up.


you should select it all with out order - and then do big select for the 2 queries with order by.


Do not use RAND() it is a terrible generator. Use a cryptographically secure generator. Depending on platform it might be arcrand(), reading from /dev/random, openSSL or some other source.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜