我要根据从另一个表顺序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字段
edit :我刚刚看到我在描述中犯了一个错误,已修复。
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)
edit 假定您的订单_by字段是数字的,您要使用的一个技巧(尽管我不确定它是否属于"最佳实践"训练营)是将订单的价值乘以字段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