help me understand why i am getting different COUNTS
Query 1
SELECT Count(*)
FROM `foo`
WHERE `status_id` = 2
AND `updated_at` < Date(Now() - INTERVAL 1 day)
AND `number` LIKE 'A390%'
OR `number` LIKE 'A391%'
OR `number` LIKE 'A392%'
results = 20000
Query 2
SELECT Count(*)
FROM `foo`
WHERE `status_id` = 2
AND `updated_at` < Date(Now() - INTERVAL 1 day)
AND ( `number` LIKE 'A390%'
OR `number` LIKE 'A391%'
OR `number` LIKE 'A392%' )
results = 14967
SELECT Count(*)
FROM `foo`
WHERE `status_id` = 2
AND `updated_at` < Date(Now() - INTERVAL 1 day)
AND `number` LIKE X
running the above query for each (A390, A391 ,A392) separately gives me:
'A390%' = 0; 'A391%' = 1496; 'A392%' = 10000;
EDIT:
Adding Screenshots to make it more clear. i had to do some photoshop to change the table name
2
Answers
http://dev.mysql.com/doc/refman/5.7/en/operator-precedence.html
Your first query’s condition is equivalent to:
The
AND
operator has higher precedence thanOR
, so your first query is equivalent to:In contrast with your second query, the conditions on
status_id
andupdated_at
apply only to the rows wherenumber LIKE 'A390%'
.The total count over the three individual queries cannot be less than the count returned by the second query, if all queries are performed on the same data. Presumably you have made a typo somewhere. The total of the individual queries could be greater, however, if any rows’
number
s satisfy more than one of theLIKE
conditions.