Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL how to make negative results possible when subtracting unsigned values?

Tags:

mysql

I have three tables joined by left join. Here's the code:

SELECT
(LEAST(`a`.`price, `b`.`price`) - `c`.`price`) AS `diff`
...
ORDER BY `diff` DESC

The problem: c.price is greater than the LEAST, thus the subtraction is negative and throws BIGINT UNSIGNED value is out of range. How can I make it NOT throw this ridiculous error?
This is result data, I'm not modifying the actual data in the table, so why does it not allow me to do this normally? I've tried CAST(LEAST(...) AS SIGNED) and casting both columns inside LEAST as signed, neither worked.

like image 244
jurchiks Avatar asked Nov 08 '12 11:11

jurchiks


People also ask

How do I stop negative values in MySQL?

You can create an int field and mark it as UNSIGNED . From MySQL 5.0 Reference Manual: INT[(M)] [UNSIGNED] [ZEROFILL] A normal-size integer. The signed range is -2147483648 to 2147483647.

How do I subtract one date from another in MySQL?

DATE_SUB() function in MySQL is used to subtract a specified time or date interval to a specified date and then returns the date. Parameter: This function accepts two parameters which are illustrated below : date – Specified date to be modified. value addunit – Here the value is date or time interval to subtract.


2 Answers

Cast as SIGNED each number before LEAST and before substract

SELECT
(LEAST(CAST(`a`.`price` AS SIGNED), CAST(`b`.`price` AS SIGNED)) - CAST(`c`.`price` AS SIGNED)) AS `diff`
...
ORDER BY `diff` DESC
like image 84
Alberto León Avatar answered Sep 28 '22 03:09

Alberto León


You may want to check the NO_UNSIGNED_SUBTRACTION operator: http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_no_unsigned_subtraction.

There are risks in using it, though: http://datacharmer.blogspot.fi/2006/11/hidden-risks-of-sql-mode.html

like image 30
kor_ Avatar answered Sep 28 '22 04:09

kor_