如何从20个最近的行中选择5个随机行?

时间:2014-07-20 16:11:34

标签: mysql

我想从一个表中选择5个随机行,但只从最近的20个行中选择。我知道这两个陈述分别是:

SELECT * FROM table ORDER BY RAND() LIMIT 5
SELECT * FROM table ORDER BY date DESC LIMIT 20

我如何组合这两个语句,以便从20个最近的行中选择5个随机行?感谢。

3 个答案:

答案 0 :(得分:3)

使用嵌套选择

 SELECT foo.* FROM (SELECT * FROM table ORDER BY date DESC LIMIT 20 ) as foo 
         ORDER BY RAND() LIMIT 5

答案 1 :(得分:1)

简单地嵌套它们:

SELECT * FROM (
    SELECT * FROM table ORDER BY date DESC LIMIT 20
) ORDER BY RAND() LIMIT 5

答案 2 :(得分:1)

查找子查询!

SELECT d.* FROM (SELECT * FROM table ORDER BY date DESC LIMIT 20) as d ORDER BY RAND() LIMIT 5;