2017-04-12 79 views
0

MySQL的选择顺序这是我的表:通过自定义列

id | val | flag 
---|-----|------ 
1 | 10 | no 
---|-----|------ 
2 | 5 | yes 
---|-----|------  
3 | 3 | yes 
---|-----|------  
4 | 25 | no 
---|-----|------  
5 | 8 | no 
---|-----|------  

基本上我想custom column desc选择id + custom column为了其中:

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端处理这个问题。

回答

1

我认为你可以这样做:

select t.* 
from t 
order by (case when flag = 'no' then val when flag = 'yes' then 2*val end) desc, id; 

注意:如果flag只能是 “否” 或 “是”,然后简化这:

select t.* 
from t 
order by (case when flag = 'no' then val else 2*val end) desc, id; 
0

你可以使用一个case声明这样

select id, val, cus from (
select id, val, case when flag = 'no' then val when flag = 'yes' then val*2 else val end as cus from my_table 
) a 
order by cus desc; 

或者,当你不希望外部选择使用的情况下也声明的顺序语句作为另一个答案建议。

如果没有出现yes或no,则可以使用case语句中的else部分来处理该情况。在我的例子中,它只是返回val

0

使用case语句。

SELECT id, 
CASE 
    WHEN flag = 'no' THEN val 
    WHEN flag = 'yes' THEN val*2 
END AS cus 
FROM table 
ORDER BY cus DESC 
0

除了戈登的解决方案(这表明你可以按列进行排序,即使他们不是结果的一部分),如果你想还包括在结果的自定义值,那么你可以写的东西像这样:

select id, if (flag='no',val,val*2) as cus 
from mytable 
order by cus desc 
0
SELECT id, 
     CASE flag 
      WHEN 'yes' THEN val*2 
      WHEN 'no' THEN val 
      ELSE val 
     END AS cus 
FROM mytable 
ORDER BY cus DESC; 
+0

这不会使用MySQL。不能在同一级别重新使用列别名。 – PhillipD

+0

严重吗? http://sqlfiddle.com/#!9/e5a46/1 –

+0

好吧,显然它确实工作...对不起。 – PhillipD