簡體   English   中英

MySQL ORDER BY取決於CASE順序ASC或DESC

[英]MySQL ORDER BY depending on CASE order ASC or DESC

我想基於從另一個表順序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看到了一些解決方案: 如何在asc和desc中動態排序2個SQL字段

編輯 :我只是看到我在描述中犯了一個錯誤,已修復。

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

如果您的列是數字,則取反有效。 如果是字符串,則可以找到另一個函數來將高值映射到低值...

無法按照您的建議條件構造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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM