简体   繁体   English

MySQL ORDER BY取决于CASE顺序ASC或DESC

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

I want based on a value queried from another table order ASC or DESC. 我想基于从另一个表顺序ASC或DESC查询的值。

So something like this: 所以像这样:

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

Is anything like that available in MySQL? MySQL提供了类似的功能吗?

I've seen for MS-SQL Server some solution: how to order 2 SQL Fields in asc and desc dynamically 我已经为MS-SQL Server看到了一些解决方案: 如何在asc和desc中动态排序2个SQL字段

EDIT : I just saw I made a mistake in the description, fixed. 编辑 :我只是看到我在描述中犯了一个错误,已修复。

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

negation works if your column is numeric. 如果您的列是数字,则取反有效。 if it's a string, you might be able to find another function to map high values to low values... 如果是字符串,则可以找到另一个函数来将高值映射到低值...

T-SQL statements can't be constructed conditionally in the manner your suggesting. 无法按照您的建议条件构造T-SQL语句。

You need to construct your query into a varchar, then perform an EXEC against the constructed string, along the lines of the following: 您需要将查询构造为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)

EDIT Presuming your order_by field is numeric, one trick you employ (although I'm not sure it would fall into the "best practices" camp) would be to multiply the value of the order by field by -1 to reverse the default order, eg 编辑假设您的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