我有以下几栏:
a | null
x | f
null | a
i | n
我需要两列都按字母顺序排序,并在底部使用空值,例如:
a | a
i | f
x | n
null | null
反正在mysql中有这样做吗?
每个列必须彼此独立地排序,然后按照该值在每个值的位置重新组合行。使用ROW_NUMBER()
窗口功能:
select t1.col1, t2.col2
from (
select col1, row_number() over(order by col1 is null, col1) rn
from tablename
) t1 inner join (
select col2, row_number() over(order by col2 is null, col2) rn
from tablename
) t2 on t2.rn = t1.rn
请参见demo。或使用CTE:
with
cte1 as (select col1, row_number() over(order by col1 is null, col1) rn from tablename),
cte2 as (select col2, row_number() over(order by col2 is null, col2) rn from tablename)
select cte1.col1, cte2.col2
from cte1 inner join cte2
on cte2.rn = cte1.rn
请参见demo。结果:
| col1 | col2 |
| ---- | ---- |
| a | a |
| i | f |
| x | n |
| null | null |
[要单独对2列进行排序,最后是否为空?
对于MySql 5.x,这是一个按π排序的解决方案:
-- sample data
drop table if exists test;
create table test (col1 varchar(8), col2 varchar(8));
insert into test (col1, col2) values
('a', null), ('x', 'f'), (null, 'a'), ('i', 'n');
-- initiating variables
set @rn1:=0, @rn2:=0;
-- query that links on calculated rownumbers
select col1, col2
from (select @rn1:=@rn1+1 as rn, col1 from test order by coalesce(col1,'π') asc) q1
left join (select @rn2:=@rn2+1 as rn, col2 from test order by coalesce(col2,'π') asc) q2
on q1.rn = q2.rn
order by q1.rn;
结果:
col1 col2
a a
i f
x n
NULL NULL
在MySql 8.0中,可以使用窗口函数ROW_NUMBER
代替变量。
select col1, col2
from (select row_number() over (order by coalesce(col1,'π') asc) as rn, col1 from test) q1
left join (select row_number() over (order by coalesce(col2,'π') asc) as rn, col2 from test where col2 is not null) q2
on q1.rn = q2.rn
order by q1.rn;
对db <>小提琴here的测试>
要单独对2列进行排序,最后是否为空?
对于MySql 5.x,这是一个按π排序的解决方案:
-- sample data
drop table if exists test;
create table test (col1 varchar(8), col2 varchar(8));
insert into test (col1, col2) values
('a', null), ('x', 'f'), (null, 'a'), ('i', 'n');
-- initiating variables
set @rn1:=0, @rn2:=0;
-- query that links on calculated rownumbers
select col1, col2
from (select @rn1:=@rn1+1 as rn, col1 from test order by coalesce(col1,'π') asc) q1
left join (select @rn2:=@rn2+1 as rn, col2 from test order by coalesce(col2,'π') asc) q2
on q1.rn = q2.rn
order by q1.rn;
结果:
col1 col2
a a
i f
x n
NULL NULL
在MySql 8.0中,可以使用窗口函数ROW_NUMBER
代替变量。
select col1, col2
from (select row_number() over (order by coalesce(col1,'π') asc) as rn, col1 from test) q1
left join (select row_number() over (order by coalesce(col2,'π') asc) as rn, col2 from test where col2 is not null) q2
on q1.rn = q2.rn
order by q1.rn;
对db <>小提琴here]的测试>