As described in the SELECT Syntax:
The HAVING is applied almost the last, just before sending items to the client, without optimization.
In other words, it is applied after performing a grouping operation (unlike WHERE , which is performed before any grouping operation). See WHERE vs HAVING .
Therefore, your current query first generates a result set from the following:
SELECT COUNT(domain) AS `sum domains`, file FROM `table` GROUP BY Number
Take a look at sqlfiddle :
| SUM DOMAINS | FILE |
---------------------------
| 2 | aaa.com_1 |
| 2 | bbb.com_1 |
| 1 | eee.com_1 |
As you can see, the values selected for the file column are just one of the values from each group, as described in MySQL Extensions for GROUP BY :
The server can select any value from each group, therefore, if they do not match, the selected values are undefined.
Then your current query filters these results according to your HAVING :
HAVING COUNT(Number) > 1 AND file LIKE '%\_1'
With the file values selected above, each individual group meets the second criterion; and the first two groups correspond to the first criterion. Therefore, the results of a full query :
| SUM DOMAINS | FILE |
---------------------------
| 2 | aaa.com_1 |
| 2 | bbb.com_1 |
Following your comments above , you want to filter the entries on file before grouping and then filter the resulting groups for those that contain more than one match. So use WHERE and HAVING respectively (and select Number instead of file to identify each group):
SELECT Number, COUNT(*) AS `sum domains` FROM `table` WHERE file LIKE '%\_1' GROUP BY Number HAVING `sum domains` > 1
Take a look at sqlfiddle :
| NUMBER | SUM DOMAINS |
------------------------
| 222 | 2 |