简体   繁体   English

如何使用mysql对基于基本整数的varchar id进行排序

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

Testcase_id in my system are varchar and generated by trigger and I want to sort them on basis of the integer value of the varchar id . 我的系统中的testcase_id是varchar,由触发器生成,我想根据varchar id的整数值对它们进行排序。 I have been so far used three queries but not working at all. 到目前为止,我已经使用了三个查询,但是根本无法使用。 I have also tried with the function which converts string to integer. 我也尝试过将字符串转换为整数的函数。 Here I am mentioning that function also and my query well in this query i have not used function. 在这里,我也提到了该功能,在此查询中,我的查询没有使用功能。

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

output(of query): 输出(查询):

查询结果集

You have to use -1 instead of 2 inside SUBSTRING_INDEX : 您必须在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

According to the manual : 根据手册

Returns the substring from string str before count occurrences of the delimiter delim. 出现定界符delim 之前,从字符串str返回子字符串。 If count is positive , everything to the left of the final delimiter (counting from the left ) is returned. 如果count为 ,则返回最后定界符左侧的所有内容(从left计数)。 If count is negative , everything to the right of the final delimiter (counting from the right ) is returned. 如果count为负数 ,则返回最后定界符右边的所有内容(从右边开始计数)。

Demo here 在这里演示

use Cast 使用演员表

CAST(col AS UNSIGNED)

or REPLACE with CAST 或用CAST REPLACE

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

Your query :- 您的查询 :-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM