2015-07-19 46 views
0

這個查詢:SQLite的:......除了... ORDER BY RANDOM()

SELECT colour FROM ColourView EXCEPT SELECT colour FROM SkinColourExceptionsView WHERE race = 'Human' ORDER BY RANDOM() LIMIT 1

產生如下異常:1st ORDER BY term does not match any column in the result set

然而,改變ORDER BY RANDOM()ORDER BY colour能夠產生結果(按顏色按字母順序排序而非隨機排列)。以下暗示ORDER BY RANDOM() LIMIT 1應該工作:Select random row from an sqlite table。有人可以解釋爲什麼我的查詢不起作用嗎?

回答

1

compound query中,ORDER BY項(s)必須與結果集中的某個列相匹配。

您可以解決此限制通過移動複合查詢爲子查詢:

SELECT colour 
FROM (SELECT colour FROM ColourView 
     EXCEPT 
     SELECT colour FROM SkinColourExceptionsView WHERE race = 'Human') 
ORDER BY random() 
LIMIT 1; 

或者,重寫查詢,使用不同的過濾機制:

SELECT colour 
FROM ColourView 
WHERE colour NOT IN (SELECT colour 
        FROM SkinColourExceptionsView 
        WHERE race = 'Human') 
ORDER BY random() 
LIMIT 1; 
+0

這兩個答案很好地工作,解釋是上衣!謝謝一堆先生。 –