2010-04-10 32 views
17

我的查詢字符串是這樣的:如何使MYSQL查詢結果ORDER BY條件順序?

SELECT ... FROM maintable 
LEFT JOIN table1 on (maintable.id = table1.idx) 
LEFT JOIN table2 on (table1.idy = table2.idy) 
LEFT JOIN table3 on (table2.idz = table3.idz) 
WHERE (condition1 OR condition2 OR condition3) 
AND maintable.status = static 

//condition1 & condition2 & condition3 are kind of 
table3.idz = 101, table3.idz = 3, maintable.id IN (1,2,3,4), and so on 

對於結果我想滿足condition1首先被退回,則滿足condition2條目,並最終滿足condition3項條目。有任何想法嗎?

+1

你的情況有區別嗎?如果不是,如果一個條目滿足多個條件會怎樣?例如,如果一個條目符合條件1和條件3,那麼應該如何對符合條件1和條件2的條目進行排序? – 2010-04-10 09:58:25

+0

不限制在這裏,所以我想可能首先遇到第一個回報? – Edward 2010-04-10 10:00:32

回答

24

爲了得到你想要的順序排序,在ORDER BY使用條件,但經過他們使用DESC

SELECT * 
FROM person 
WHERE (condition1 OR condition2 OR condition3) 
AND maintable.status = static 
ORDER BY 
    condition1 DESC, 
    condition2 DESC, 
    condition3 DESC 

如果這不起作用,因爲您的查詢比較複雜,那麼你可以使用布爾邏輯來縮小查詢(A OR B OR C) AND D(A AND D) OR (B AND D) OR (C AND D)那麼你可以使用下面的查詢:

SELECT * 
FROM person 
WHERE (condition1 OR condition2 OR condition3) 
AND maintable.status = static 
ORDER BY 
    condition1 AND static DESC, 
    condition2 AND static DESC, 
    condition3 AND static DESC 

AND static在這裏沒有必要,因爲所有的行都會返回它,但是在一個更復雜的例子中(你也可以返回一些非靜態的行),那麼你必須這樣做。

+1

+1,以便識別需要「DESC」! – 2010-04-10 10:15:05

+0

條件如何(我有我的查詢字符串更新)是像table.id = 123?我嘗試了ORDER BY句子,但沒有效果。 – Edward 2010-04-10 10:19:01

+0

@Relax:我之前給出的例子可以正常工作。無論如何,我已經更新了它,因爲我猜測你的實際查詢比你允許我們知道的要複雜得多。 – 2010-04-10 10:23:30

7

這應該工作:

ORDER BY condition1, condition2, condition3 

例如

ORDER BY (weight > 500), (height > 3), (height < 2) 
+0

謝謝,但它不起作用,它可能是因爲我的實際查詢字符串更復雜,我已更新 – Edward 2010-04-10 10:16:39