使用 WHERE、AND、OR 的 SQL 选择语句
我想使用 MySQL 执行 SELECT
查询。我的目标是选择兽医数据库中的所有狗,这些狗是 sex=male
和 fur=short
和(color=black 或 size=big
code>)
注意:我想选择黑色或体型较大的狗。他们不必满足这两个要求。他们只需要满足其中一个即可。
我已经写了下面的 SQL 语句,但我不确定我是否正确:
SELECT name, sex, fur, color
FROM dogs
WHERE TRUE sex='male' AND fur='short' AND color='black' OR size="big";
如果我的措辞太混乱,请原谅。
I would like to perform a SELECT
query with MySQL. My goal is to select all the dogs in a vet database that would be sex=male
and fur=short
and (color=black or size=big
)
Note: I want to select dogs that are either black or size is big. They don't have to fulfill the 2 requirements. They just need to fulfill either one.
I have written the SQL statement below but I'm not not sure if I'm right:
SELECT name, sex, fur, color
FROM dogs
WHERE TRUE sex='male' AND fur='short' AND color='black' OR size="big";
Pardon my phrasing if it's too confusing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据 MySQL 运算符优先级
AND
的优先级高于OR
。所以
C1 AND C2 OR C3
将被视为(C1 AND C2) OR C3
要覆盖默认优先级,您需要使用括号:
C1 AND (C2 OR C3)
在您的情况下,正确的查询是:
According to Operator precedence for MySQL
AND
has higher precedence thanOR
.So
C1 AND C2 OR C3
will be treated as(C1 AND C2) OR C3
To override the default precedence you need to use parenthesis as:
C1 AND (C2 OR C3)
In your case the right query is:
确保添加括号,以便正确评估 OR 条件。
Make sure to add parentheses, so the OR condition gets evaluated correctly.
您在描述目标时使用括号的方式是正确的。语法是:
The way you use parentheses in the description of your goal is correct. The syntax is:
我已经使用过这个及其工作原理;
I have used this and its working;
从狗中选择姓名、性别、皮毛、颜色,其中性别 = '雄性',皮毛 = '短' 且(颜色 = '黑色' 或尺寸 = '大');
select name, sex, fur,color from dogs where sex ='male' and fur = 'short' and (color ='black' or size ='big');