MySQL 带有 WHERE、AND、OR 的 SQL 选择语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3581784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Select Statement with WHERE, AND, OR
提问by dave
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
)
我想SELECT
用 MySQL执行查询。我的目标是选择兽医数据库中的所有狗,它们将是sex=male
和fur=short
和(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:
我写了下面的 SQL 语句,但我不确定我是否正确:
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.
如果太混乱,请原谅我的措辞。
回答by codaddict
According to Operator precedence for MySQLAND
has higher precedence than OR
.
根据运算符优先级,MySQL 的AND
优先级高于OR
.
So
C1 AND C2 OR C3
will be treated as (C1 AND C2) OR C3
所以
C1 AND C2 OR C3
将被视为(C1 AND C2) OR C3
To override the default precedence you need to use parenthesis as:C1 AND (C2 OR C3)
要覆盖默认优先级,您需要使用括号作为:C1 AND (C2 OR C3)
In your case the right query is:
在您的情况下,正确的查询是:
SELECT name, sex, fur, color
FROM dogs
WHERE sex='male' AND fur='short' AND (color='black' OR size="big");
回答by Lance Rushing
Make sure to add parentheses, so the OR condition gets evaluated correctly.
确保添加括号,以便正确评估 OR 条件。
SELECT name, sex, fur, color
FROM dogs
WHERE sex='male' AND fur='short' AND (color='black' OR size='big');
回答by cherouvim
The way you use parentheses in the description of your goal is correct. The syntax is:
您在目标描述中使用括号的方式是正确的。语法是:
SELECT name, sex, fur, color
FROM dogs
WHERE sex="male" AND fur="short" AND (color="black" OR size="big");
回答by user1350714
I have used this and its working;
我已经使用了这个及其工作;
SELECT name, sex, fur, color
FROM dogs
WHERE sex="male" AND fur="short" AND (color="black" || size="big");
回答by Shiwangini
select name, sex, fur,color from dogs where sex ='male' and fur = 'short' and (color ='black' or size ='big');
从狗中选择名称,性别,毛皮,颜色,其中性别 ='男性' 和毛皮 = '短' 和(颜色 ='黑色' 或大小 ='大');