这是我的 table :
id | val | flag
---|-----|------
1 | 10 | no
---|-----|------
2 | 5 | yes
---|-----|------
3 | 3 | yes
---|-----|------
4 | 25 | no
---|-----|------
5 | 8 | no
---|-----|------
基本上我想选择id +自定义列
按自定义列desc
排序,其中:
custom column = val (if flag = no)
custom column = val * 2 (if flag = yes)
我的选择结果应该输出:
| id | cus |
|----|-----|
| 4 | 25 |
|----|-----|
| 1 | 10 |
|----|-----|
| 2 | 10 |
|----|-----|
| 5 | 8 |
|----|-----|
| 3 | 6 |
|----|-----|
不要问我尝试了什么,因为我是 mysql 新手。我知道如何在 php 中执行此操作,但我想最好从 mysql 端处理此操作。
最佳答案
我认为你可以这样做:
select t.*
from t
order by (case when flag = 'no' then val when flag = 'yes' then 2*val end) desc, id;
注意:如果flag
只能是“no”或“yes”,则将其简化为:
select t.*
from t
order by (case when flag = 'no' then val else 2*val end) desc, id;
关于MySQL 按自定义列选择顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43380110/