包含数字和文本的varchar字段的order子句

时间:2018-02-14 13:12:54

标签: sql postgresql sql-order-by

sql:

create table users(username varchar(256));

insert into users values ('1112');
insert into users values ('126');
insert into users values ('124');
insert into users values ('cats');

select * from users order by username;

生成订单:1112, 124, 126, cats

有没有办法让订单子句按字母顺序排列,但如果是数字则为数字,即:124, 126, 1112,cats

我试过了:

select * from users order by ('000'::varchar || username)

但这没有帮助

2 个答案:

答案 0 :(得分:1)

一些丑陋的黑客来得快:

t=# select * from users 
order by ascii(username), regexp_replace(username,'[a-z]','0','g')::bigint, username;
                    username
------------------------------------------------
 124
 126
 1112
 cats
(4 rows)

有想法

  • ascii数字代码是升序和字母之前
  • regexp_replace将对数字进行排序,而不是数字
  • 最后按字母顺序排列

答案 1 :(得分:1)

select *
from users 
order by
  case
    when username ~ '^[0-9]+$' then username::bigint
    else null
  end,
  username;

表示数据:

insert into users values ('1112');
insert into users values ('126');
insert into users values ('124');
insert into users values ('22');
insert into users values ('cats');

给出:

"22"
"124"
"126"
"1112"
"cats"