我必须通过升序数值来排序 sql 结果。我的代码是这样的:
ORDER BY CAST(`baseData` AS DECIMAL(10,2)) {$dir} ";
它工作得很好,但有一个问题:它将所有 NULL 值放在底部,我认为它认为它们像“0”。我需要将所有 NULL 值放在底部,我该如何修改它?
试试这个 SQL
对于 MYSQL
ORDER BY COALESCE(CAST(`baseData` AS DECIMAL(10,2)),0)
对于甲骨文
ORDER BY NVL(CAST(baseData AS DECIMAL(10,2)),0)
MySQL 5.5.30 架构设置:
create table test(
t varchar(5)
);
insert into test
values('123'),('234'),('222'),(NULL);
查询 1:
select coalesce(cast(t as decimal(10,2)),0)
from test
order by coalesce(cast(t as decimal(10,2)),0);
结果:
| COALESCE(CAST(T AS DECIMAL(10,2)),0) |
----------------------------------------
| 0 |
| 123 |
| 222 |
| 234 |
如果你想把所有的 Nulls 放在首位
ORDER BY CAST(`baseData` AS DECIMAL(10,2)) NULLS FIRST
如果你想把所有的 Nulls 放在底部
ORDER BY CAST(`baseData` AS DECIMAL(10,2)) NULLS LAST
如果您希望 Nulls 被视为 0,请像 Pheonix 一样将它们转换为
ORDER BY Nvl(CAST(`baseData` AS DECIMAL(10,2)), 0) -- Oracle, MS SQL
ORDER BY IfNull(CAST(`baseData` AS DECIMAL(10,2)), 0) -- MySQL
如果您希望 Nulls 排在最后,但显示为 0
select ...
Nvl(CAST(`baseData` AS DECIMAL(10,2)), 0) -- Oracle, MS SQL
...
order by CAST(`baseData` AS DECIMAL(10,2)) NULLS LAST
是的,它有效:
ORDER BY baseData = '', CAST(`baseData` AS DECIMAL(10,2)) {$dir} ";