我创建了两个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)
据我了解,首先它将JOIN的结果与other_records.practice匹配。两者都应返回相同的结果集。然后,据我所知,它将匹配细节为null或细节与ERROR和ERROR BY PRACTICE不匹配的地方。我不确定为什么括号会在这里有所作为?
答案 0 :(得分:4)
在布尔逻辑中,和运算符&&
优先于或运算符||
。
因此,当您编写此代码时:
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')
...因此将不同的结果添加到第二条语句中。