是否可以从 mysql 中的选定字段值或 if 语句定义 Order By 的排序方向?

发布于 2024-10-06 16:28:56 字数 278 浏览 0 评论 0原文

举例来说,我有一个这样的查询:

select table1.somedate AS date1, IF(3 = :some_query_parameter, ASC, DESC) AS SortOrder FROM table1 ORDER BY date1 SortOrder;

我想做的是将 SortOrder 字段中的值放入 ORDER BY 的 ASC 或 DESC 方向,以便根据字段的值升序或降序排序。

我的猜测是这是不可能的,但我想我还是会问。

Say for instance I had a query like this:

select table1.somedate AS date1, IF(3 = :some_query_parameter, ASC, DESC) AS SortOrder FROM table1 ORDER BY date1 SortOrder;

What I'm trying to do is put the value from the SortOrder field into the ORDER BY's ASC or DESC direction so that it is sorted ascending or descending based on the value of the field.

My guess is that this cannot be done, but I figured I'd ask anyway.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅笑轻吟梦一曲 2024-10-13 16:28:56

如果您尝试根据变量按 ASC 或 DESC 顺序对日期进行排序,您可以尝试在 ORDER BY 子句中使用 CASE 语句:

SELECT table1.somedate AS date1
FROM table1
ORDER BY 
CASE WHEN :some_query_parameter = 3 THEN table1.somedate ELSE '1/1/1900' END ASC,
CASE WHEN :some_query_parameter <> 3 THEN table1.somedate ELSE '1/1/1900' END DESC

仅使用上面的 ORDER BY 子句之一,另一个将始终评估为共同的价值观。 ELSE 子句中的值必须计算为与 table1.somedate 相同的数据类型。

If you are trying to sort the date in either ASC or DESC order based on a variable, you could try using a CASE statement in the ORDER BY clause:

SELECT table1.somedate AS date1
FROM table1
ORDER BY 
CASE WHEN :some_query_parameter = 3 THEN table1.somedate ELSE '1/1/1900' END ASC,
CASE WHEN :some_query_parameter <> 3 THEN table1.somedate ELSE '1/1/1900' END DESC

Only one of the ORDER BY clauses above will be used, the other will consistently evaluate to a common value. The value in the ELSE clause must evaluate to the same datatype as table1.somedate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文