AND and OR execution order issues in SQL statements


question

I encountered a problem yesterday while writing database SQL. The root of the problem lies in the execution priority of the AND and OR keywords of the SQL statement. Let's test this problem.

Scenes

1. There is a student table Student, the table fields include Id (user primary key), Name (user name), Grade (grade), Class (class), Sex (gender). as follows:


Table Structure

2. Import ten pieces of test data into the table, as follows:


table data

3. Now it is necessary to find out the female students of grade 1 whose gender is female, or the female students of grade 2 whose gender is female. The SQL statement is as follows:
    select * from student where sex='女' and grade=1 or class=2

However, the result of the sql query does not meet the requirements, and the execution result is as follows:

Results of the

In the execution result, the male student in class 2 is also queried, and the result is obviously incorrect.

4. Modify the SQL statement and add parentheses. as follows:

select * from student where sex='女' and (grade=1 or class=2)

The result of the sql query meets the requirements, and the execution result is as follows:

Results of the

analyze

From the above scenario, the crux of the problem lies in the execution order of AND and OR.
Looking up the data, the priority of relational operators is as follows:NOT >AND >OR
if there is an OR condition after where, OR will automatically separate the left and right query conditions.
Just like the first statement in the above scenario, his query condition is divided into two parts (or):

1、sex='女' and grade=1
2class=2

This is to query the female students in grade 1 and the students in class 2. Does not meet the requirements of the original query.
Then the solution is to use parentheses to distinguish the order of execution.
Just like the second statement in the above scenario, the query condition is divided into two parts (and):

1、 sex='女' 
2、 (grade=1 or class=2)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326179147&siteId=291194637