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)
但这没有帮助
答案 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)
有想法
答案 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"