Mysql查询rand()和order by

时间:2013-01-14 08:41:58

标签: mysql sql random sql-order-by

您好我正在尝试按位置ASC排序一些随机结果。

这是我的疑问:

SELECT `location`, `route`
FROM (`foo`)
WHERE `location` != ''
ORDER BY  RAND(), `location` ASC
LIMIT 8 

问题是它是随机的,但是不是通过“位置”ASC命令,如果我这样做:

SELECT `location`, `route`
FROM (`foo`)
WHERE `location` != ''
ORDER BY  `location` ASC,RAND()
LIMIT 8 

它不是随机的。

我怎样才能同时获得RAND()ORDER BY location ASC

1 个答案:

答案 0 :(得分:3)

您需要嵌套语句/查询:

SELECT *
FROM (
    SELECT `location`, `route`
    FROM `foo`
    WHERE `location` != ''
    ORDER BY RAND()
    LIMIT 8) AS `temp`
ORDER BY `location` ASC;