There are city library tables in the database, including countries, provinces and cities.
Example: in Guangdong province (including Guangdong province itself), find the name of "Guangzhou" record
First, the conditions in Guangdong province are: parentid = 2 Or Id =2
The name is "Guangzhou" condition is: name= ' Guangzhou '
After merging:
SELECT * FROM dbo. City
WHERE parentid = 2 OR Id = 2 and name= ' Guangzhou '
But the results are as follows:
The reason for the above result is that the or has a lower priority than and, the above SQL is equivalent to:
SELECT * FROM dbo. City
WHERE ParentID = 2 OR (Id = 2 and name= ' Guangzhou ')
What we need is the data that satisfies the first condition while satisfying the second condition.
SELECT * FROM dbo. City
WHERE (parentid = 2 OR Id = 2) and name= ' Guangzhou '
Use parentheses to combine multiple small conditions into one large condition.
Precedence of and and or in SQL Server