2012-10-25 159 views
1

我希望基於從另一個表順序查詢的值ASC或DESC。MySQL ORDER BY取決於CASE order ASC或DESC

因此,像這樣:

SELECT * 
FROM table 
ORDER BY 
    CASE (SELECT sorting from table2 WHERE table2.id = ?) 
     WHEN 1 THEN table.date ASC END 
     WHEN 0 THEN table.date DESC END 
    END 

是類似的東西可以在MySQL?

我已經看到了MS-SQL Server的一些解決方案:how to order 2 SQL Fields in asc and desc dynamically

編輯:我剛纔看到我在描述犯了一個錯誤,固定。

回答

3
order by if((select sorting from table2 where table2.id = ?) = 1, 
    unix_timestamp(table.date), -unix_timestamp(table.date)) 

如果您的列是數字,否定將起作用。如果它是一個字符串,你可能能夠找到另一個函數來將高值映射到低值...

+0

這是不正確的。這個人想要按不同的領域排序不同的tabel。從問題中可以看出,字段排序的值僅爲0或1,因此通過排序或排序進行排序是無用的 –

+0

這實際上有效!我可以轉換日期,沒問題。 – Sam

+0

不,該字段的值實際上是* date *值,而不是0或1,所以這種技術可能很有用。 +1即可享受創意,開箱即用的選擇。 –

2

T-SQL語句不能以您建議的方式有條件地構建。

需要構建查詢到一個varchar,然後對構造的字符串執行EXEC,大意如下的行:

Declare @QueryString varchar(100) 
Declare @Direction int 

Select @direction = sorting 
    from table2 
where table2.id=? //from your original, not clear how you are providing it 

Set @QueryString = 'Select * from table order by yourField ' + case when @direction=1 then 'ASC' else 'DESC' end 

Exec (@QueryString) 

編輯意味着你的ORDER_BY領域是數字,您使用的一個技巧(雖然我不確定它會落入「最佳實踐」陣營)將按字段乘以-1的順序來逆轉默認順序,例如

Select @Direction = sorting 
    from table2 
where table2.id=? 

Select * 
    from table 
    order by (case when @direction=1 then -1 else 1 end) *yourField 
+0

這不是微軟要使用t-sql –

+0

爆炸。誤讀OP的帖子,認爲他需要T-SQL解決方案。 –