Question

I have a webapp that uses DataTables with server side processing. I have some SQL Queries that arbitrarily regroups data in columns, so I get queries like this:

SELECT case `column`
WHEN 'value1' then 'group1'
WHEN 'value2' then 'group1'
ELSE `column` END AS `column grouped`, SUM(`2010`)
GROUP BY `colonne grouped`

Now, I add some filtering based on user input, and I do like this:

SELECT case `column`
WHEN 'value1' then 'group1'
WHEN 'value2' then 'group1'
ELSE `column` END AS `column grouped`, SUM(`2010`)
GROUP BY `column grouped`
HAVING `column grouped` LIKE '%test%'

And it still work just fine, but my woes come when I try to make the whole thing case insentive, and so I do:

SELECT case `column`
WHEN 'value1' then 'group1'
WHEN 'value2' then 'group1'
ELSE `column` END AS `column grouped`, SUM(`2010`)
GROUP BY `colonne grouped`
HAVING UPPER(`column grouped`) LIKE '%test%'

And now I get "#1054 - Unknown column 'column grouped' in 'having clause'"

AS a workaround, I do something like this:

SELECT case `column`
WHEN 'value1' then 'group1'
WHEN 'value2' then 'group1'
ELSE `column` END AS `column grouped` , SUM(`2010`)
GROUP BY `colonne grouped`
HAVING UPPER(case `column`
WHEN 'value1' then 'group1'
WHEN 'value2' then 'group1'
ELSE `column` END) LIKE '%test%'

But this is not really convenient. Anyone knows why I'm not able to use UPPER with custom alias ?

I am using MySQL 5.5 by the way.

Était-ce utile?

La solution

According to docs you cannot use functions in the HAVING clause:

The SQL standard requires that HAVING must reference only columns in the GROUP BY clause or columns used in aggregate functions. However, MySQL supports an extension to this behavior, and permits HAVING to refer to columns in the SELECT list and columns in outer subqueries as well.

You're restricted to columns you've already retrieved. I don't know if there's a technical reason behind but that's what the SQL standard mandates.

Autres conseils

try to make UPPER in WHERE clause

      SELECT case `column`
     WHEN 'value1' then 'group1'
     WHEN 'value2' then 'group1'
     ELSE `column` END AS `column grouped`, SUM(`2010`)
     WHERE UPPER(`column grouped`) LIKE '%test%'
     GROUP BY `colonne grouped`
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top