This may be a problem that is easy to be ignored. First, we need to be clear:
In MySQL, AND takes precedence over OR. That is to say, without the limitation of parentheses (), the AND statement is always executed first AND then the OR statement.
For example:
select * from table where condition1 and condition2 or condition3 Equivalent to select * from table where (condition 1 AND 2) OR condition 3 select * from table where condition1 and condition2 or condition3 and condition4 Equivalent to select * from table where (condition 1 AND condition 2) OR (condition 3 AND condition 4)
Here are some examples:
Test table data:
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for book -- ---------------------------- DROP TABLE IF EXISTS `book`; CREATE TABLE `book` ( `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `author` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `price` decimal(10, 2) DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of book -- ---------------------------- INSERT INTO `book` VALUES (1, 'PHP', 'mate', 21.00); INSERT INTO `book` VALUES (2, 'JAVA', 'kaven', 23.00); INSERT INTO `book` VALUES (3, 'JAVA senior', 'loose', 45.00); INSERT INTO `book` VALUES (4, 'GO', 'jim', 46.00); INSERT INTO `book` VALUES (5, 'GO Design', 'json', 76.00); INSERT INTO `book` VALUES (6, 'PHP Advanced programming', 'bate', 67.00); INSERT INTO `book` VALUES (7, 'Python', 'jim', 66.00); INSERT INTO `book` VALUES (8, 'Python Design', 'mali', 54.00); INSERT INTO `book` VALUES (9, 'GO programming', 'kaven', 86.00); INSERT INTO `book` VALUES (11, 'Python3', 'jim', 55.00); SET FOREIGN_KEY_CHECKS = 1;
Query method 1:
SELECT * FROM book WHERE author='jim' OR author='json' AND name='PHP';
The above query is equivalent to:
SELECT * FROM book WHERE author='jim' OR (author='json' AND name='PHP');
Then the above query results are easy to understand.
Query method 2:
SELECT * FROM book WHERE name='PHP' AND author='jim' OR author='json';
The above query is equivalent to:
SELECT * FROM book WHERE (name='PHP' AND author='jim') OR author='json';
Query method 3:
SELECT * FROM book WHERE name='GO' AND (author='jim' OR author='json');
This is easy to understand. Understand the priority of and or. These queries are not "understanding confusion".