这个可能是容易被忽略的问题,首选我们要清楚:
MySQL中,AND的执行优先级高于OR。也就是说,在没有小括号()的限制下,总是优先执行AND语句,再执行OR语句。
比如:
select * from table where 条件1 AND 条件2 OR 条件3
等价于
select * from table where ( 条件1 AND 条件2 ) OR 条件3 select * from table where 条件1 AND 条件2 OR 条件3 AND 条件4
等价于
select * from table where ( 条件1 AND 条件2 ) OR ( 条件3 AND 条件4 )
来点事例深入理解下:
测试表数据:
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高级', 'loose', 45.00);
INSERT INTO `book` VALUES (4, 'GO', 'jim', 46.00);
INSERT INTO `book` VALUES (5, 'GO设计', 'json', 76.00);
INSERT INTO `book` VALUES (6, 'PHP高级编程', 'bate', 67.00);
INSERT INTO `book` VALUES (7, 'Python', 'jim', 66.00);
INSERT INTO `book` VALUES (8, 'Python设计', 'mali', 54.00);
INSERT INTO `book` VALUES (9, 'GO编程', 'kaven', 86.00);
INSERT INTO `book` VALUES (11, 'Python3', 'jim', 55.00); SET FOREIGN_KEY_CHECKS = 1;
查询方式1:
SELECT * FROM book WHERE author='jim' OR author='json' AND name='PHP';
上面的查询等价于:
SELECT * FROM book WHERE author='jim' OR (author='json' AND name='PHP');
那么上面的查询结果就很好理解了。
查询方式2:
SELECT * FROM book WHERE name='PHP' AND author='jim' OR author='json';
上面的查询等价于:
SELECT * FROM book WHERE (name='PHP' AND author='jim') OR author='json';
查询方式3:
SELECT * FROM book WHERE name='GO' AND (author='jim' OR author='json');
这个就很好理解了。了解and or的优先级。这些查询也就不是呢么"理解混淆"了。