The following example is just a test, but I guess one can construct something that actually does make sense. Anyway, I don't understand why it doesn't work. MySQL reports [42S22][1054] Unknown column 'document0_.age' in 'having clause'. I tested the same query with many other databases(PostgreSQL, DB2, Oracle, SQL Server, etc.), MySQL is the only to complain about this.
Could anyone explain to me why this doesn't work? I know I can just put in the age column into the GROUP BY clause and be done with it, but this is generated code and I'd need to add a special case for handling this MySQL problem which is why I'd like to better understand the issue. Is this only problematic for CASE WHEN statements or are there other expressions(e.g. nested function calls) that might also lead to such an error?
select count(versions1_.id) as col_0_0_
from Document document0_
left outer join document_version versions1_ on document0_.id=versions1_.document_id
group by
document0_.id,
case when document0_.id=document0_.age and document0_.age<4 then '2' when document0_.id=4 then '4' else '3' end
having
case when document0_.id=document0_.age and document0_.age<4 then '2' when document0_.id=4 then '4' else '3' end='2'
EDIT: I just tried out whether function calls migh also be problematic and indeed they are. The following also fails with the same error message.
select count(versions1_.id) as col_0_0_
from Document document0_
left outer join document_version versions1_ on document0_.id=versions1_.document_id
group by
document0_.id,
POW(document0_.id,document0_.age)
having
POW(document0_.id,document0_.age)=2
I begin to believe that MySQL does not detect that the expressions are equal and thus tries to re-evaluate them when doing the HAVING clause part. Am I right?