2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLのFLOAT、DOUBLE(5.0.3より前ではDECIMALも)は注意して扱う

Last updated at Posted at 2015-07-16

自分のためのメモ

System

mysql> SHOW VARIABLES LIKE "%version%";
+-------------------------+----------+
| Variable_name           | Value    |
+-------------------------+----------+
| innodb_version          | 5.6.22   |
| protocol_version        | 10       |
| slave_type_conversions  |          |
| version                 | 5.6.22   |
| version_comment         | Homebrew |
| version_compile_machine | x86_64   |
| version_compile_os      | osx10.9  |
+-------------------------+----------+
7 rows in set (0.01 sec)

What happens?

ユーザのスコアテーブルを考えましょう

CREATE TABLE IF NOT EXISTS `scores` (
`id` int(10) unsigned NOT NULL,
  `score` double NOT NULL,
  `user_id` int(11) NOT NULL
);

INSERT INTO `scores` (`id`, `score`, `user_id`) VALUES
(1, 2, 1),
(2, 0.2, 2),
(3, 3, 2),
(4, 0.2, 2);
mysql> SELECT * FROM `scores`;
+----+-------+---------+
| id | score | user_id |
+----+-------+---------+
|  1 |     2 |       1 |
|  2 |   0.2 |       2 |
|  3 |     3 |       2 |
|  4 |   0.2 |       2 |
+----+-------+---------+
4 rows in set (0.00 sec)

合計しましょう

mysql> SELECT SUM(`score`) AS `total_score` FROM `scores`;
+-------------+
| total_score |
+-------------+
|         5.4 |
+-------------+
1 row in set (0.00 sec)

想定どおり

ユーザ毎に合計しましょう

mysql> SELECT SUM(`score`) AS `total_score_per_user`, `user_id` FROM `scores` GROUP BY `user_id`;
+----------------------+---------+
| total_score_per_user | user_id |
+----------------------+---------+
|                    2 |       1 |
|   3.4000000000000004 |       2 |
+----------------------+---------+
2 rows in set (0.00 sec)

!!!

Why?

FLOATDOUBLE はおおよその値である(5.0.3 より前では DECIMAL は文字列として保存されるが、計算は FLOAT として計算される)ため

Reference sites

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?