在MySQL中将VARCHAR的一部分排序为INT

时间:2012-10-18 07:17:15

标签: mysql sql-order-by

我试图通过CAST(pid AS SIGNED)将字符串的一部分排序为整数但没有成功。

我想我需要像这样的伪代码:CAST ON REGX('^islandora(/d?)$') OF pid AS SIGNED

doFields表具有以下结构:

+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| pid           | varchar(64)  | NO   | MUL | NULL    |       |
| ownerId       | varchar(255) | YES  |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+

这里是样本数据:

+----------------+---------+
| pid            | ownerId |
+----------------+---------+
| islandora:1050 | 8       |
| islandora:1052 | 8       |
| islandora:1053 | 8       |
| islandora:1054 | 8       |
| islandora:1055 | 8       |
+----------------+---------+

3 个答案:

答案 0 :(得分:3)

如何替换单词islandora:并将其转换为int。

SELECT *
FROM tableName
ORDER BY CAST(REPLACE(pid, 'islandora:', '') AS SIGNED) ASC

答案 1 :(得分:2)

试试这个:

order by 
       cast(substr(pid,locate(':',pid)+1) as SIGNED)    

如果整数部分总是4个字母长度,那么

  Order by
      cast(right(pid,4) as SIGNED)  

答案 2 :(得分:1)

尝试使用此ORDER BY -

ORDER BY SUBSTRING_INDEX(pid, ':', -1) * 1;