且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

mysql:将分数字符串转换为数字

更新时间:2023-02-03 08:25:06

我认为这不是你应该在查询中做的事情,而是在存储时计算它并将计算值保存在它旁边的表中文本值.

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

但是请注意,如果数据无效",这可能会导致问题.如果显示0/0 km",则可能会失败,如果包含此处无数据",则也可能会失败.

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.