mysql : turn fraction strings into number

前端 未结 3 1094
隐瞒了意图╮
隐瞒了意图╮ 2021-01-24 08:54

I have strings like... \"3/4\" and \"5/9\" and some like... \"1/2 km\" and \"3/4 degree\" stored in mysql columns.

I would like to convert them into numbers. In first c

3条回答
  •  半阙折子戏
    2021-01-24 09:30

    The above didn't quite work for me so came up with this which does. The query works for '10', '3/4' and '10 3/4'. Obviously you should replace the constructed rows at the bottom with your string or a selected value from a table:

    SELECT 
        IF (
            LOCATE(' ',fraction) > 0 OR LOCATE('/',fraction) = 0,
            SUBSTRING_INDEX(SUBSTRING_INDEX(fraction,'/','1'),' ','1')
            ,0
        ) AS `integer`,
        IF (
            LOCATE('/',fraction) > 0,
            SUBSTRING_INDEX(SUBSTRING_INDEX(fraction,'/','1'),' ','-1'),
            0
        ) AS numerator,
        SUBSTRING_INDEX(fraction,'/','-1') AS denominator,
        (SELECT `integer`) + ((SELECT numerator) / (SELECT denominator)) AS `decimal`
    FROM (
        SELECT '10 3/4' AS fraction
        UNION SELECT '10'
        UNION SELECT '3/4'
    ) t;
    

提交回复
热议问题