mysql : turn fraction strings into number

前端 未结 3 1041
隐瞒了意图╮
隐瞒了意图╮ 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:26

    I think this isn't something you should do in a query, but rather calculate it when it is stored and save the calculated value in the table next to its text value.

    But if you want to, you can use some string functions to slice up the value and the do the math yourself:

    select
      x.Multiplier / x.Divider as Result
    from
        (select
          cast( substr( t.String, 
                        1, 
                        locate('/', t.String) - 1) 
                as decimal) 
            as Multiplier,
          cast( substr( t.String, 
                        locate('/', t.String) + 1, 
                        locate( ' ', 
                                concat(t.String, ' '))) 
                as decimal) 
            as Divider
        from
          YourTable t) x
    

    Note however, that this may cause trouble if the data is 'invalid'. If it says '0/0 km', it may fail, if it contains 'no data here' it may fail as well.

提交回复
热议问题