如何使用 mysql 根据其中的整数对 varchar id 进行排序

How to sort varchar id on basis integer in it using mysql

Testcase_id 在我的系统中是 varchar 并由触发器生成,我想根据 varchar id 的整数值对它们进行排序。到目前为止,我已经使用了三个查询但根本没有工作。我也尝试过将字符串转换为整数的函数。在这里我也提到了那个函数,我在这个查询中很好地查询了我没有使用过的函数。

select t.Testcase_id, 
       CONVERT(SUBSTRING_INDEX('t.Testcase_id','_',2),UNSIGNED INTEGER) as num 
from testcase_master t 
order by num

输出(查询):

使用 Cast

CAST(col AS UNSIGNED)

REPLACECAST

CAST(REPLACE(testcase_id,'TC_CTU_','') AS UNSIGNED)

您的查询:-

select t.Testcase_id, 
       CAST(REPLACE(testcase_id,'TC_CTU_','') AS UNSIGNED) as num 
from testcase_master t 
order by num

您必须在 SUBSTRING_INDEX 中使用 -1 而不是 2:

select t.Testcase_id,      
       CONVERT(SUBSTRING_INDEX(t.Testcase_id,'_', -1),UNSIGNED INTEGER) as num 
from testcase_master t 
order by num

根据 manual:

Returns the substring from string str before count occurrences of the delimiter delim. If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned.

Demo here