2016-09-27 71 views
0

我有一個域,子域,路徑,動作,類型,用戶的表,我有結果根據操作字段排序。mysql:如何根據字段結果得到不同的順序

類型表示記錄的類型(2 =域,3 =子域,4 =路徑)。

對於action的結果= a然後按行動順序asc,path desc,subdomain desc,user desc;

用於與行動= b的結果然後以通過作用ASC,ASC子域,路徑ASC,用戶降序;

我需要上述所有內容都在基於域,子域,路徑選擇的一條select語句中。選擇將開始像:

select action, user 
from table1 
where (domain = 'testdomain.com' and type = 2) 
or (domain = 'testdomain.com' and subdomain = 'sub1'and type = 3) 
or (domain = 'testdomain.com' and path = 'path1' and type = 4) 
and (user is null or user = 'smith') 
order by ... 

在此先感謝。

更新...德魯報告這是重複的。我在參考的問題中沒有太多的內容,但是我跳過了這個查詢。查詢沒有工作(語法錯誤):

select action, type, user from filterList 
where (domain = 'testdomain.com' and type = 2) 
or (domain = 'testdomain.com' and subdomain = 'sub1' and type = 3) 
or (domain = 'testdomain.com' and path = 'path1' and type = 4) 
and (user is null or user = 'smith') 
order by `action` asc, 
CASE `action` 
WHEN 'a' THEN order by path desc, subdomain desc, user desc 
WHEN 'b' THEN order by subdomain asc, path asc, user desc; 
+0

此查詢將返回多個行嗎?例如,如果它返回5行,你怎麼知道要使用哪個'action'值? – Santi

+0

是的,會有多行返回。結果中可能有三個動作= a和兩個動作= b。 –

+0

我重新打開了習題 – Drew

回答

1

這是可能的,但它看起來有點怪,你在正確的軌道上:

order by `action` asc, 
CASE `action` WHEN 'a' THEN path ELSE NULL END DESC, 
CASE `action` WHEN 'a' THEN subdomain ELSE NULL END DESC, 
CASE `action` WHEN 'a' THEN user ELSE NULL END DESC, 
CASE `action` WHEN 'b' THEN subdomain ELSE NULL END ASC, 
CASE `action` WHEN 'b' THEN path ELSE NULL END ASC, 
CASE `action` WHEN 'b' THEN user ELSE NULL END DESC 

我猜語法錯誤你得到的是因爲你不能在CASE語句中放置ORDER BY子句。

相關問題