[英]Mysql ORDER BY varchar column stored as number
I have a mysql column (staffid) which format is varchar(11). 我有一个mysql列(staffid),其格式为varchar(11)。 This column is used to store staff id, which are generally 1,2,3............40,60... I can't use int format for that column as for contractual staff it stores id as cont-1, while for regular staff it stores id as integer 1,2,3... While I am trying to fetch array using a ORDER BY clause with that column, rows are not fetching with correct order. 此列用于存储人员ID,通常为1,2,3 ............ 40,60 ...对于合同人员,我不能将int格式用于该列将id存储为cont-1,而对于普通员工,则将id存储为整数1,2,3 ...当我尝试使用带有该列的ORDER BY子句获取数组时,行的获取顺序不正确。 My sql query is: 我的SQL查询是:
SELECT * FROM database ORDER BY CAST('staffid' as UNSIGNED INTEGER) ASC
How can I format that varchar column in mysql query so that for regular staff it treats as integer column as order by that column? 我该如何格式化mysql查询中的varchar列,以便对于普通员工而言,按该列的顺序将其视为整数列?
the proper syntax is, 正确的语法是
SELECT *
FROM `database`
ORDER BY CAST(staffid AS UNSIGNED) ASC
since you have mentioned that there are some ids with this format cont-1
. 因为您已经提到过,有些ID的格式为cont-1
。 probably you can add WHERE
clause to filter specific ID, 可能您可以添加WHERE
子句以过滤特定ID,
SELECT *
FROM `database`
WHERE staffid NOT LIKE 'cont%'
ORDER BY CAST(staffid AS UNSIGNED) ASC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.