【问题标题】:IF statement on ORDER BY returns only one valueORDER BY 的 IF 语句只返回一个值
【发布时间】:2014-03-07 09:57:33
【问题描述】:

感谢您的收看......

我想得到一组行,如果 col_3 在某些条件下并且 col_1 的最大值大于 5,则返回 col_1、col_2、col_3 的 4 行,按 col_1 排序,如果值小于 5,则返回按 col_2 排序

如果最大值(col_1)>5

select col_1, col_2, col_3 from TABLE where col_3 = 'some condition' order by col_1  desc limit 4;

其他

select col_1, col_2, col_3 from TABLE where col_3 = 'some condition' order by col_2  desc limit 4;

分开效果很好,但下一个查询只返回一行,按 col_2 排序。

select col_1, col_2, col_3 from TABLE where col_3 = 'some condition' order by if(max(col_1) > 5, col_1, col_2)  desc limit 4;

对不起,我的英语太短了... 再次感谢您的帮助 祝你有美好的一天:)

【问题讨论】:

标签: mysql


【解决方案1】:

尝试(SELECT max(col_1) FROM TABLE) > 5 而不是max(col_1) > 5

select col_1, col_2, col_3 from TABLE where col_3 = 'some condition' order by if((SELECT max(col_1) FROM TABLE) > 5, col_1, col_2)  desc limit 4;

【讨论】:

  • 还请注意,对于大型表,此查询可能不会很好地执行,如果您将它与 php 或任何其他服务器端一起使用,请尝试先获取计数并在您的 ORDER BY IF 条件下使用它。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
  • 2020-07-30
  • 2021-07-04
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多