Question

MySQL 5.5 Database SQL:

CREATE TABLE `test` (
  `id` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `age` decimal(19,0) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
insert into `test` (`id`,`age`) values(`1`,`1234567890123456789`);
insert into `test` (`id`,`age`) values(`2`,`1234567890123456787`);

When i use this SQL:

select * from test where age=1234567890123456787 ;

everything is ok,but when i use this SQL:

select * from test where age='1234567890123456787' ;

two recodes will show.I don't know the reason that when my code use String type to search a filed that a decimal type ,when my code cast it to Long ,all is ok.

Why MySQL can't report a error or auto cast the unsuited type ,i don't know this design for what? When i use Oracle , this problem does't exist.

Was it helpful?

Solution

This is just yet another Floating-Point value problem.

When comparing a decimal value with a string, they are compared as floating-point (real) numbers.

Below is the explanation from the MySQL document:

Comparisons that use floating-point numbers (or values that are converted to floating-point numbers) are approximate because such numbers are inexact. This might lead to results that appear inconsistent:

mysql> SELECT '18015376320243458' = 18015376320243458;
        -> 1
mysql> SELECT '18015376320243459' = 18015376320243459;
        -> 0

Such results can occur because the values are converted to floating-point numbers, which have only 53 bits of precision and are subject to rounding:

mysql> SELECT '18015376320243459'+0.0;
        -> 1.8015376320243e+16

Furthermore, the conversion from string to floating-point and from integer to floating-point do not necessarily occur the same way. The integer may be converted to floating-point by the CPU, whereas the string is converted digit by digit in an operation that involves floating-point multiplications.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top