使用带负数的 'Greater than' 运算符

Using 'Greater than' operator with a negative number

我需要 运行 针对包含正数和负数的列以及 return 所有比选定值 <> 的行进行多次查询,但是,如果所选值为负数,当我使用 'Greater than' 运算符时,它不会 returning 预期结果。

Please note that when the selected value is a negative number it should be returning both positive and negative numbers, and it seems to be excluding the negative numbers from the results.

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

T3.Width中包含的值为:

0.90,(0.70),(0.70),(0.70),(0.70),(1.00),(1.00),(1.00),(1.00),(0.90),(0.55),(0.50)

因此结果应该是:

0.90,(0.70),(0.70),(0.70),(0.70),(0.55),(0.50)

然而 returned 的结果是:

0.90

最简单的解决方案当然是在 table 中使用 DECIMAL()FLOAT 列。

由于您正在使用 VARCHAR() 类型并且更愿意继续使用 VARCHAR,RDBMS 没有正确地将 () 包含的值视为负值,而是试图将字符串转换为整数(结果为零,比较不正确)。

解决 () 封闭的底片:

使用 () 封闭的负值,您可以 REPLACE() 开盘 (-REPLACE() 闭盘 ) 什么都没有,导致值类似于 -0.70,但它仍然是 字符串 到 MySQL。然后您必须 CAST it to a decimal value 进行 < > 比较。

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

在 VARCHAR 列中使用常规负值

如果将它们更改为常规负数但保留 VARCHAR 类型,则不需要所有嵌套 REPLACE() 但仍需要将其转换为 DECIMAL(10,2).

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

Example 2:

你强制进行文本比较

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

使用数字比较, '-.80'-.80 的区别只是引号。

当您按数值比较时,查询将 return 预期结果

如果您必须使用引号,请使用 CAST('-.80' AS DECIMAL(12,2))

这给出了 2 位小数和 10 位数字,对于大多数演员来说应该足够了,但如果需要可以调整

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