Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 使用NULL对多个文本列进行排序_Mysql_Sql_Sorting_Null_Alphabetical - Fatal编程技术网

Mysql 使用NULL对多个文本列进行排序

Mysql 使用NULL对多个文本列进行排序,mysql,sql,sorting,null,alphabetical,Mysql,Sql,Sorting,Null,Alphabetical,我有以下专栏: a | null x | f null | a i | n 我需要两列按字母顺序排序,底部为空,如下所示: a | a i | f x | n null | null mysql中有这样做的方法吗?每一列必须独立于另一列进行排序,然后按照每个值的位置按顺序重新组合行。 使用行号()窗口功能: select t1.col1, t2.col2 from ( select col1, row_number() over(order by co

我有以下专栏:

a    | null
x    | f
null | a
i    | n
我需要两列按字母顺序排序,底部为空,如下所示:

a    | a
i    | f
x    | n
null | null

mysql中有这样做的方法吗?

每一列必须独立于另一列进行排序,然后按照每个值的位置按顺序重新组合行。
使用
行号()
窗口功能:

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
请参阅。

或使用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
请参阅。

结果:


要独立排序这两列,最后为空

对于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中,可以使用窗口函数
行数
代替变量

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;

在dbfiddle上测试你的mysql版本是什么?版本-8.0.18你的答案可能在这里
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;