如何在Mysql中对ASC中的条形码字符串进行排序

时间:2014-06-19 06:00:17

标签: mysql

您好我有一个表名self_instrument,其中有一列Id_number,即其仪器的条形码.. 我想按照升序中的Id_number显示记录 如下所示

ACA1/STD/01-->this is barcode
ACA2/STD/01
ACA3/STD/01

ACB1/STD/01
ACB2/STD/01
.
.
.
.

mysql查询是

SELECT Distinct Id_number  
FROM  `self_instrument` 
WHERE `Id_number` != ''   
ORDER BY if( LOCATE( '/', `Id_number` ) >0, 
            SUBSTRING( `Id_number` , LOCATE( '/', `Id_number` ) +1 ) ,
            concat( 'z', `Id_number` ) ) , 
        if( LOCATE( '/', `Id_number` ) >0, 
            SUBSTRING( `Id_number` , 1, 3 ) , 
            concat( 'z', `Id_number` ) ) , 
        CAST( if( LOCATE( '/', `Id_number` ) >0, 
                  SUBSTRING( `Id_number` , 4, LOCATE( '/', `Id_number` ) -4 ) , 
                  concat( 'z', `Id_number` ) ) AS UNSIGNED )

但是当我运行它时会显示输出

WT/CI-EQ/2011/500   -->these are some exceptional barcode in the records 
BLORE/DHTC/ALAB/50-600/01   --->same as above 
AC/INST/021     
AC/INST/021     
ACA1/STD/01         
ACA2/STD/01         
ACA3/STD/01     
ACA4/STD/01     
ACA5/STD/01     
ACA6/STD/01

所以按照asc的顺序,它需要显示 先是在最后一个W 和系列图案 就好像 ACA1 / STD / 01
ACA2 / STD / 01 ACA3 / STD / 01

2 个答案:

答案 0 :(得分:0)

select * from     
(    
SELECT Distinct Id_number  
FROM  `self_instrument` 
WHERE `Id_number` != ''   
ORDER BY if( LOCATE( '/', `Id_number` ) >0, 
            SUBSTRING( `Id_number` , LOCATE( '/', `Id_number` ) +1 ) ,
            concat( 'z', `Id_number` ) ) , 
        if( LOCATE( '/', `Id_number` ) >0, 
            SUBSTRING( `Id_number` , 1, 3 ) , 
            concat( 'z', `Id_number` ) ) , 
        CAST( if( LOCATE( '/', `Id_number` ) >0, 
                  SUBSTRING( `Id_number` , 4, LOCATE( '/', `Id_number` ) -4 ) , 
                  concat( 'z', `Id_number` ) ) AS UNSIGNED )

) tbl order by 1 asc;

你能试试吗?它应该工作。

答案 1 :(得分:0)

您首先按/之后的子字符串排序。我想你希望这是最后一个标准:

SELECT Distinct Id_number  
FROM  `self_instrument` 
WHERE `Id_number` != ''   
ORDER BY 
        -- Sort first by 3-letter prefix 
        if( LOCATE( '/', `Id_number` ) >0, 
            SUBSTRING( `Id_number` , 1, 3 ) , 
            concat( 'z', `Id_number` ) ) , 
        -- Then by number after last `/`
        CAST(IF( LOCATE ('/', Id_number ),
                SUBSTRING_INDEX( Id_number, '/', -1), 
                CONCAT( 'z', Id_number) ) AS UNSIGNED ),
        -- Then by number after the prefix
        CAST( if( LOCATE( '/', `Id_number` ) >0, 
                  SUBSTRING( `Id_number` , 4, LOCATE( '/', `Id_number` ) -4 ) , 
                  concat( 'z', `Id_number` ) ) AS UNSIGNED ),
        -- Finally by everything after first `/`
        if( LOCATE( '/', `Id_number` ) >0, 
            SUBSTRING( `Id_number` , LOCATE( '/', `Id_number` ) +1 ) ,
            concat( 'z', `Id_number` ) )