2011-10-03 75 views
3

問題你應該看看我想在這裏做的,但它不工作UNION和ORDER BY在MySQL

$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」。

+0

聯合查詢通常僅能在最後一個查詢是聯合在一起的order by語句,這適用於工會的結果。使用括號(如下面Erwin的答案)可以讓您單獨查詢並繞過此限制。 –

回答

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 question
consult the fine manual

+1

另外@CanSpice,每個子選擇都不需要自己的別名嗎?並且'UNION ALL'會快得多,尤其是因爲這裏不會有重疊。 – Johan

+0

@Johan;這些不是實際的子選擇,所以它們不是。我添加了一個鏈接到mysql文檔。但是'聯盟全部'好點! –

4

通過或LIMIT應用於爲了將個人選擇,將子句括起來,括號內的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)