我的数据库中有一个列,其中包含格式为
的数字1-1 1-2 2-1 2-2 等等
我希望能够按“第一个数字”,“第二个数字”订购
我已经尝试过了:
ORDER BY CAST('session_number' as signed) ASC
但是那不能正确地排序第二个数字。
答案 0 :(得分:3)
按第一部分的顺序排序,将子字符串转换为已签名:
CAST(SUBSTRING_INDEX(session_number, '-', 1) AS SIGNED) ASC,
CAST(SUBSTRING_INDEX(session_number, '-', -1) AS SIGNED) ASC
或创建已排序项目的视图:
CREATE VIEW v_sessions_ordered_by_session_number
AS
SELECT *
FROM sessions
ORDER BY
CAST(SUBSTRING_INDEX(session_number, '-', 1) AS SIGNED) ASC,
CAST(SUBSTRING_INDEX(session_number, '-', -1) AS SIGNED) ASC;
,然后将“视图”用作表:
SELECT some_field, session_number FROM v_sessions_ordered_by_session_number;
但是更好的解决方案是:
将session_number
设置为十进制,例如:1.1
,1.2
,2.1
等
如果不允许修改字段类型,则只需
另外创建:session_number_order
字段并保留十进制数据
答案 1 :(得分:1)
尝试一下:
select nums
from (
select nums, position('-' in nums) `pos` from tbl
) a
order by cast(substring(nums, 1, pos - 1) as signed),
cast(substring(nums, pos + 1, length(nums) - pos) as signed)
在order by
子句中,首先您按第一个数字排序(在破折号-
之前),第二次排序是根据第二个数字(在破折号之后)。