Using 'Greater than' operator with a negative number

别等时光非礼了梦想. 提交于 2019-12-07 00:35:30

The easiest solution is of course to use a DECIMAL() or FLOAT column in the table.

Since you are working with VARCHAR() types and prefer to continue working with VARCHAR, the RDBMS is not correctly treating () enclosed values as negatives, and instead attempting to cast the strings to an integer (which results in zero, and an incorrect comparison).

Working around the () enclosed negatives:

Using the ()-enclosed negative values, you can REPLACE() the opening ( with a - and REPLACE() the closing ) with nothing, resulting in a value like -0.70, but it is still a string to MySQL. You must then CAST it to a decimal value for the < > comparison.

SELECT Width
FROM T3
WHERE
  /* Replace the ( to -, and the ) with nothing
   * then cast it to a decimal value
   */ 
  CAST(REPLACE(REPLACE(Width, '(', '-'), ')', '') AS DECIMAL(10,2)) > '-0.8'

Example in action

Working with regular negative values in a VARCHAR column

If you change them to regular negative numbers but retain the VARCHAR type, you don't need all the nested REPLACE() but you will still need to cast it to a DECIMAL(10,2).

SELECT Width
FROM T3
WHERE 
  CAST(Width AS DECIMAL(10,2)) > '-0.8'

Example 2:

your forcing a text comparison

SELECT T3.*    
FROM Rules T3
WHERE T3.Width > -.80;

uses a numerical comparison, The differnce being '-.80' vs -.80 is just the quotes.

When you compare by numerical value the query will return the expected results

if you HAVE to use quotes, use CAST('-.80' AS DECIMAL(12,2))

This gives 2 decimal places and 10 digits, Should be enough for most casts, though adjust if needed

If both arguments in a comparison operation are strings, they are compared as strings.

http://dev.mysql.com/doc/refman/5.0/en/type-conversion.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!