在sql中添加括号产生不同的结果

vltsax25  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(324)

我创建了两条sql语句,第二条给出的结果少得多。唯一的区别是我在第二个查询中添加了其他括号:

SELECT COUNT(*)
FROM records
JOIN other_records ON records.other_record_id = other_records.id
WHERE other_records.practice = 'Medical' && 
records.details IS NULL || 
(records.details <> 'ERROR' && records.details <> 'ERROR BY PRACTICE');

+----------+
| COUNT(*) |
+----------+
|   342668 |
+----------+
1 row in set (3.42 sec)

SELECT COUNT(*) FROM records JOIN other_records 
ON records.other_record_id = other_records.id 
WHERE other_records.practice = 'Medical' && 
(records.details IS NULL || (records.details <> 'ERROR' && records.details <> 'ERROR BY PRACTICE'));

+----------+
| COUNT(*) |
+----------+
|   193899 |
+----------+
1 row in set (0.46 sec)

据我所知,首先它将匹配的结果与其他联合记录。做法是医疗。此时两者应返回相同的结果集。然后,据我所知,它将匹配要么细节是空的,要么细节不匹配的错误和实践中的错误。我不知道为什么括号在这里起作用?

h5qlskok

h5qlskok1#

在布尔逻辑中,and运算符 && 优先于or运算符 || .
所以,当你写这个的时候:

WHERE other_records.practice = 'Medical' && 
records.details IS NULL ||
(records.details <> 'ERROR' && records.details <> 'ERROR BY PRACTICE')

……相当于:

WHERE (other_records.practice = 'Medical' && records.details IS NULL)
||
(records.details <> 'ERROR' && records.details <> 'ERROR BY PRACTICE')

…因此你的第二个陈述的结果不同。

相关问题