简体   繁体   中英

SQL Select Statement with WHERE, AND, OR

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.

According to Operator precedence for MySQL AND has higher precedence than OR .

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:

SELECT name, sex, fur, color 
FROM dogs 
WHERE sex='male' AND fur='short' AND (color='black' OR size="big");

Make sure to add parentheses, so the OR condition gets evaluated correctly.

SELECT name, sex, fur, color 
FROM dogs 
WHERE sex='male' AND fur='short' AND (color='black' OR size='big');

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");

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");

从性别为'male'且毛皮='short'并且(颜色='black'或size ='big')的狗中选择名字,性别,皮毛,颜色;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM