MySQL中的UNION和ORDER BY问题

时间:2011-10-03 17:32:25

标签: mysql sql sql-order-by union

你应该看看我在这里要做什么,但它没有用

$getquery = "SELECT * 
FROM highscore 
WHERE score >= '$score'
ORDER BY score ASC
LIMIT 6

UNION

SELECT * 
FROM highscore 
WHERE score < '$score'
ORDER BY score DESC
LIMIT 5";

mysql_error()返回:“ORDER BY和UNION的使用不当”。

2 个答案:

答案 0 :(得分:9)

尝试:

$getquery = "(SELECT * 
FROM highscore 
WHERE score >= '$score'
ORDER BY score ASC
LIMIT 6)

UNION ALL -- guaranteed to be beneficial in this case as Johan commented

(SELECT * 
FROM highscore 
WHERE score < '$score'
ORDER BY score DESC
LIMIT 5)";

请参阅comments to my answer on the related questionconsult the fine manual

答案 1 :(得分:4)

要将ORDER BY或LIMIT应用于单个SELECT,请将该子句放在括起SELECT的括号内:

(SELECT * 
 FROM highscore 
 WHERE score >= '$score'
 ORDER BY score ASC
 LIMIT 6)

UNION

(SELECT * 
 FROM highscore 
 WHERE score < '$score'
 ORDER BY score DESC
 LIMIT 5)