I have the following query:
SELECT (RAND() * (SELECT MAX(id) FROM frag.test))
Results in: -2.36835027969671e+18
id is a: id bigint(20) unsigned
The things is that
SELECT MAX(id) FROM frag.test
Results in 15783548581713655808
And if I place the literal number instead of a select it works
SELECT (RAND() * 15783548581713655808
Results in 1.50243050315076e+19
Also the following query:
SELECT RAND()*id from frag.test;
Results in:
+----------------------+
| RAND()*id |
+----------------------+
| 2.90739099802377e+18 |
| 3.18790581714312e+18 |
| 4.55299756382674e+18 |
| 8.53310890373737e+18 |
| 5.32382972831492e+18 |
| 1.13192831652015e+19 |
+----------------------+
The problem appears to happen only when MAX() is used.
Anyone have any thoughts on what might be happening here?
Thank you!
EDIT:
As pointed out by coge, this has something to do with casting.
I changed the query to
SELECT (RAND() * (SELECT cast(MAX(id) as decimal(30,10)) FROM frag.test));
And now it works as expected!
I believe there may be a problem with data types. Rand() returns a floating-point value. I’m not a MySQL expert, but I wonder whether floating-points inheritly convert to int.
Try either converting the result of Rand() to an int or converting the bigint to a float or decimal.