表pc -
code model speed ram hd cd price
1 1232 500 64 5.0 12x 600.0000
10 1260 500 32 10.0 12x 350.0000
11 1233 900 128 40.0 40x 980.0000
12 1233 800 128 20.0 50x 970.0000
2 1121 750 128 14.0 40x 850.0000
3 1233 500 64 5.0 12x 600.0000
4 1121 600 128 14.0 40x 850.0000
5 1121 600 128 8.0 40x 850.0000
6 1233 750 128 20.0 50x 950.0000
7 1232 500 32 10.0 12x 400.0000
8 1232 450 64 8.0 24x 350.0000
9 1232 450 32 10.0 24x 350.0000
期望的输出-
model speed hd
1232 450 10.0
1232 450 8.0
1232 500 10.0
1260 500 10.0
查询 1 -
SELECT model, speed, hd
FROM pc
WHERE cd = '12x' AND price < 600
OR
cd = '24x' AND price < 600
查询 2 -
SELECT model, speed, hd
FROM pc
WHERE cd = '12x' OR cd = '24x'
AND price < 600
查询 1 确实工作正常,但是当我尝试将查询减少为仅一次使用价格时,它没有显示正确的结果..让我知道我在逻辑中遗漏了什么。
Find the model number, speed and hard drive capacity of the PCs having 12x CD and prices less than $600 or having 24x CD and prices less than $600.
最佳答案
由于 AND
出现在 OR
之前,您的查询被解释为:
WHERE (cd = '12x') OR ((cd = '24x') AND (price < 600))
或者,换句话说:所有具有 12x CD 的 PC,或具有 24x CD 的 PC < 600 美元
您需要使用括号来指定操作顺序:
WHERE (cd = '12x' OR cd = '24x') AND price < 600
或者,您可以使用 IN
:
WHERE cd IN ('12x', '24x') AND price < 600
另请参阅:http://dev.mysql.com/doc/refman/5.5/en/operator-precedence.html
关于mysql - 选择数据时mysql查询中的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14619365/