Description:
I have a query with column alias, group by and having. It's getting altered when I add an order by.
This strange behavior is only happening in 5.6.16 and 5.6.21 (which I was using in development, over Windows)
It was not happening on 5.5.41 and 5.5.43 (which I had in production, over Linux) So I downgraded my local MySQL to 5.5.* and the query worked as expected.
How to repeat:
I'm not sure on how to repeat, but I will do my best in order to show this strange behavior
My query:
SELECT
a.*
, if(u.status = 1 AND a.acre_aprobado = 0, 5, u.status) tipo
FROM acreditado a
JOIN users u ON (`a`.`acre_id` = `u`.`id`)
WHERE `acre_test` = 0
GROUP BY `a`.`acre_id`
HAVING tipo = '1'
#ORDER BY `acre_aprobado` ASC
The result in both 5.5.* and 5.6.*: (without the order by)
============================================================
acre_id | obac_id | ... | tipo
27 | 23 | ... | 1
37 | 22 | ... | 1
44 | 22 | ... | 1
46 | 22 | ... | 1
============================================================
Now the result when I add order by:
5.5.*
============================================================
acre_id | obac_id | ... | tipo
27 | 23 | ... | 1
37 | 22 | ... | 1
44 | 22 | ... | 1
46 | 22 | ... | 1
============================================================
5.6.*
============================================================
acre_id | obac_id | ... | tipo
25 | 24 | ... | 0
32 | 24 | ... | 0
44 | 22 | ... | 1
46 | 22 | ... | 1
============================================================
As you can see, in 5.5.* everything works as expected, but in 5.6.* order by is modifying the result, and it's even making "having" don't filter
I created an SQL fiddle
http://sqlfiddle.com/#!9/c928c/8
First run the query as is, and then uncomment "order by" and run it.
I read something about MySQL Extensions to GROUP BY from the post Why does MySQL allow HAVING to use SELECT aliases? that might have some to do with this issue, but I wonder why the different behavior between 5.5.* and 5.6.*
SHOW CREATE TABLE tablename;for both tables. – ypercubeᵀᴹ May 08 '15 at 16:03GROUP BYat all if both theacreditado.acre_idand theusers.idare primary keys in the respective tables. – ypercubeᵀᴹ May 08 '15 at 16:09ORDER BY acre_aprobado ASCis using a column that has a lot of duplicate values. It should not be expected to be consistent. – ypercubeᵀᴹ May 08 '15 at 16:18- Please refer to the SQLfiddle.
- I do need a group by since I'm joining "acreditado" with another table, from which I'm getting a count. It's not on the fiddle since it's not needed. The issue can be reproduced without this other table.
- Play within that fiddle. Remove and add the "order by" and see how the result changes. Order by should not change the rows in the result, it should only change the order. But in 5.6.* it's anulating the having (showing rows with tipo = 0) and it only happens in 5.6.* Not in 5.5.*
– helpse May 08 '15 at 17:13