如何在 运行 查询时更改数据类型(不在 PHP 内)
How to change data type when running query (not inside PHP)
说明
在 MySQL 中对小数进行精确数学运算时,它会将字符串处理为 Float 而不是 Fixed 例如,如果我们在数据库中有以下列(金额类型为 DECIMAL(43,20)
)
+--------------------------+
| amount |
+--------------------------+
| 0.20000000000000000000 |
+--------------------------+
运行以下PHP代码
$amount_to_add = "0.1";
$stmt = $dbh->prepare("UPDATE table SET amount = amount + :amount");
$stmt->bindValue("amount", $amount_to_add);
$stmt->execute();
会产生这样的结果:
+--------------------------+
| amount |
+--------------------------+
| 0.30000000000000004000 |
+--------------------------+
注意额外的 0.00000000000000004000
因为 $amount_to_add
是字符串
因为我需要使用 BC Math 函数,它的输出是 always string
And i can't convert it to double/float inside PHP because it will lose precision and decimal points
问题
我应该如何将其传递给 MySQL 以将其视为小数(固定)而不是不需要更改 PHP 中的字符串类型的字符串(浮点)?
是否可以在 运行 查询时声明数据类型?所以它将 MySQL
中的字符串更改为十进制
UPDATE table SET amount = amount + CAST(:amount AS DECIMAL(X, Y))
说明
在 MySQL 中对小数进行精确数学运算时,它会将字符串处理为 Float 而不是 Fixed 例如,如果我们在数据库中有以下列(金额类型为 DECIMAL(43,20)
)
+--------------------------+
| amount |
+--------------------------+
| 0.20000000000000000000 |
+--------------------------+
运行以下PHP代码
$amount_to_add = "0.1";
$stmt = $dbh->prepare("UPDATE table SET amount = amount + :amount");
$stmt->bindValue("amount", $amount_to_add);
$stmt->execute();
会产生这样的结果:
+--------------------------+
| amount |
+--------------------------+
| 0.30000000000000004000 |
+--------------------------+
注意额外的 0.00000000000000004000
因为 $amount_to_add
是字符串
因为我需要使用 BC Math 函数,它的输出是 always string
And i can't convert it to double/float inside PHP because it will lose precision and decimal points
问题
我应该如何将其传递给 MySQL 以将其视为小数(固定)而不是不需要更改 PHP 中的字符串类型的字符串(浮点)?
是否可以在 运行 查询时声明数据类型?所以它将 MySQL
中的字符串更改为十进制UPDATE table SET amount = amount + CAST(:amount AS DECIMAL(X, Y))