sql - 为什么只能在 where 条件下以文本形式找到浮点值

标签 sql postgresql

为什么没有引用参数就找不到行?

CREATE TABLE test (id integer, value real);
INSERT INTO test VALUES (1, 0.1);

不起作用:

SELECT * FROM test where value = 0.1;
 id | value
----+-------
(0 rows)

有效!

SELECT * FROM test where value = '0.1';
 id | value
----+-------
  1 |   0.1
(1 row)

最佳答案

你应该避免 inexact data types(like real) :

Inexact means that some values cannot be converted exactly to the internal format and are stored as approximations, so that storing and retrieving a value might show slight discrepancies. Managing these errors and how they propagate through calculations is the subject of an entire branch of mathematics and computer science and will not be discussed here, except for the following points:

  • If you require exact storage and calculations (such as for monetary amounts), use the numeric type instead.

  • If you want to do complicated calculations with these types for anything important, especially if you rely on certain behavior in boundary cases (infinity, underflow), you should evaluate the implementation carefully.

  • Comparing two floating-point values for equality might not always work as expected.

如果您坚持使用实数,请确保两个参数具有相同的数据类型:

SELECT * FROM test where value = 0.1::real;

DBFiddle Demo

关于sql - 为什么只能在 where 条件下以文本形式找到浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50559392/

相关文章:

sql - 有什么方法可以在 PostgreSQL 中的字符串值(如 eval)中执行查询?

mysql - 如果表中有空值,如何将MySQL列合并为一列?

MySQL 递归子查询

sql - Postgres ratio_to_report 函数

sql - 如何防止内部连接查询重复(Postgres)

sql - 每个 SELECT 语句都需要 FROM 子句

mysql - SQL:最大聚合和按查询分组

java - StreamedContent : Download is complete, 但文件为空

mysql - 将日期从 '01-JAN-85' 格式转换为表中 MySQL 可读的格式(来自 Postgres)

postgresql - 如何从 vagrant virtualbox 机器连接主机 PostgreSQL