我需要对字母进行排序,但是要对数字进行排序,然后再对字母进行排序?
如果我这样做...
ORDER BY name ASC
我明白了...
2d this 10
2d this 9
this item
但是我想要这个...
2d this 9
2d this 10
this item
到目前为止,我已经做到了...
ORDER BY CAST(name AS UNSIGNED) ASC
这给了我...
this item
2d this 9
2d this 10
因此它正确地d1 this 9
和d1 this 10
,但最后我需要this item
。
我一直保持这种方式,然后在遍历结果时仅检查this item
,将其存储并在循环结束后将其添加到结果中,但是有什么方法可以在其中完成所有操作sql查询?
答案 0 :(得分:1)
您可以替换字符串末尾的数字,并将其用作order by
中的第一个键:
order by regexp_replace(name, '[0-9]*$', ''),
length(name),
name
在早期版本的MySQL中,您可以更轻松地删除最后一个数字:
order by (case when name regexp ' [0-9]+$'
then left(name, length(name) - instr(reverse(name), ' '))
else name
end),
length(name),
name
Here是db <>小提琴。
答案 1 :(得分:0)
对于此示例数据,您可以使用函数substring_index()
:
select name
from tablename
order by substring_index(name, ' ', -1) + 0 = 0,
substring_index(name, ' ', -1) + 0,
name
请参见demo。
结果:
| name |
| ---------- |
| 2a this 9 |
| 2a this 10 |
| this item |