MySQL格式良好的查询不会使用相等和之间检索任何结果

时间:2014-02-24 17:25:38

标签: mysql

所以,把这些行放在桌子上

## raw_material_costs ##
id    code      family     material min_size    max_size    value
651   100005    sleeve     SAE 1020 1.21        1.24        4.48882
659   100006    sleeve     SAE 1020 1.21        1.24        6.62878

直接在SQL选项卡上运行以下查询不会返回任何这些行。如果值(在这种情况下是1.21)等于min_size或者在min_sizemax_size之间,我想获取行。 (尝试之前使用BETWEEN比较并得到相同的结果)

SELECT * FROM (`raw_material_costs`) 
WHERE `raw_material_costs`.`family` =  'sleeve' 
AND `raw_material_costs`.`material` =  'SAE 1020' 
AND (
    ( `raw_material_costs`.`min_size` = '1.21' )
    OR ( `raw_material_costs`.`min_size` >= '1.21' AND `raw_material_costs`.`max_size` <=   '1.21' )
)

EDIT1:忘记提及使用的值。

修正查询(cjg指向的解决方案[见下文])

SELECT *
FROM (`raw_material_costs`)
WHERE `raw_material_costs`.`family` =  'sleeve'
AND
`raw_material_costs`.`material` =  'SAE 1020'
AND   (
(
CAST( `min_size` as DECIMAL(10,2) ) =
1.21
  )
OR     (
CAST( `min_size` as DECIMAL(10,2) ) >= '1.21'
AND CAST( `max_size` as
DECIMAL(10,2) ) <= '1.21'
)
)

3 个答案:

答案 0 :(得分:1)

您将min_size和max_size视为sql查询中的文本字符串,尝试从最小和最大大小中删除撇号:

正如Gorkk在评论中指出的那样,你还有max_size过滤了1.21而不是1.24。

SELECT * FROM (`raw_material_costs`) 
WHERE `raw_material_costs`.`family` =  'sleeve' 
AND `raw_material_costs`.`material` =  'SAE 1020' 
AND (
    ( `raw_material_costs`.`min_size` = 1.21 )
    OR ( `raw_material_costs`.`min_size` >= 1.21 AND `raw_material_costs`.`max_size` <=   1.24 )
)

答案 1 :(得分:0)

尝试

SELECT * FROM 
`raw_material_costs`
WHERE `family` =  'sleeve' 
AND `material` =  'SAE 1020' 
AND `min_size` <= `max_size`

答案 2 :(得分:0)

如果字段的数据类型是浮点数,则数字匹配的可能性非常高,浮点数比较可能不正确,因为可能有近似值。 所以,即使你说它的1.21,它实际上可能会被保存1.20000001或1.9999999997左右。比较两个浮点数,cast到十进制并比较。

CAST(`fields` as DECIMAL(10,2)) 

类似的问题: MySQL floating point comparison issues