【问题标题】:Comparing double values in mysql not seems to be working properly比较 mysql 中的双精度值似乎无法正常工作
【发布时间】:2017-04-05 07:22:40
【问题描述】:

当我在 where 子句中比较一个浮点值时,它没有给出正确的结果。 例如

SELECT * FROM users WHERE score = 0.61

在这个查询中分数是一个double类型的列

但如果我检查分数为0.50,则上述查询有效,而我也有0.61 的记录时没有搜索其他内容

如果我使用上述查询也可以使用

SELECT * FROM users WHERE trim(score) = 0.61

【问题讨论】:

  • 分数列数据类型?
  • 是的,如果我使用 trim 函数,它就可以工作
  • 你给出的长度和小数范围是多少?
  • 你的意思是如果你这样做:score = 0.61 即使你有 score 记录也不会显示任何内容

标签: mysql database


【解决方案1】:

我建议您使用decimal 而不是float。而且它也只有 2 位小数。

这是有关如何使用它的文档。 Link.

希望这能解决你的问题。

【讨论】:

  • 如果我使用小数,它会自动在剩余的小数范围内附加 0,例如 0.61 变为 0.6100 而我不需要
  • cast('score' AS CHAR) '0.61' 试试这个
【解决方案2】:

如果您没有在浮点列中指定小数范围,我将无法在没有强制转换或修剪的情况下工作:

这很好用:

-- drop table test_float;
create table test_float(f float(6,4) , d DECIMAL(4,2));
insert into test_float values (0.5,0.5);
insert into test_float values (0.61,0.61);
select * from test_float where f = d;
select * from test_float where f = 0.61;

这不起作用:

drop table test_float;
create table test_float(f float , d DECIMAL(4,2));
insert into test_float values (0.5,0.5);
insert into test_float values (0.61,0.61);
select * from test_float;
select * from test_float where f = d;
select * from test_float where f = 0.61;
select * from test_float where CAST(f as DECIMAL(16,2)) = 0.61;

它适用于十进制范围range = 1 为什么,我真的不知道为什么?!!

【讨论】:

    猜你喜欢
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 2012-05-06
    • 2013-02-17
    • 2017-10-09
    • 2017-08-03
    相关资源
    最近更新 更多