mysql按a b c d四个字段中的最小正整数,由小到大进行排序

发表于

需求:第一张图是原始数据,第二张图中的顺序是按我的需求的排列结果。好比虚拟出来新的一列 e,e的值是abcd中的最小正整数,然后按e的大小排序。

mysql的语句:

第一种:

select *
from t1 a
left join
(
select id, min(a) minnum from
(select id, a a from t1 where a>0
union all
select id, b a from t1 where b>0
union all
select id, c a from t1 where c>0
union all
select id, d a from t1 where d>0
) t1
group by t1.id
) b
on a.id=b.id
order by b.minnum asc, b.id asc;

第二种,效率更高:

select a,b,c,d,least(if( a>0, a ,100000000),if(b>0,b,100000000),if(c>0,c,100000000),if(d>0,d,100000000)) as minVal from t1 order by minVal asc;