I have a query:
SELECT I.Id
, CAST(SUBSTRING_INDEX(GROUP_CONCAT(I.StatusId ORDER BY I.TransactionId DESC), ',', 1) AS UNSIGNED) AS StatusId
, SUM(I.RefundAmount) AS RefundAmount
FROM (
SELECT I.Id
, IT.Id AS TransactionId
, IT.StatusId
, IF(IT.TypeId = 2, IT.RefundAmount, 0) AS RefundAmount
FROM Items I
INNER JOIN ItemTransactions IT ON IT.ItemId = I.Id
WHERE I.Id = someValue
) I
GROUP BY I.Id
HAVING StatusId = 1 AND RefundAmount = 0
Where Items table has transaction records stored in ItemTransactions table. I’ve been using this type of query and works for me until this time, got some issues with the having clause.
The query works in SQL Editors but not working properly when used on stored procedures. (Don’t get me wrong, I’ve been using this query for most of my stored procedures). Debugging line per line, found that there is an issue with having clause.
As a temporary fix, I changed the query to:
SELECT I.Id
, I.StatusId
, I.RefundAmount
FROM (
SELECT I.Id
, CAST(SUBSTRING_INDEX(GROUP_CONCAT(I.StatusId ORDER BY I.TransactionId DESC), ',', 1) AS UNSIGNED) AS StatusId
, SUM(I.RefundAmount) AS RefundAmount
FROM (
SELECT I.Id
, IT.Id AS TransactionId
, IT.StatusId
, IF(IT.TypeId = 2, IT.RefundAmount, 0) AS RefundAmount
FROM Items I
INNER JOIN ItemTransactions IT ON IT.ItemId = I.Id
WHERE I.Id = someValue
) I
GROUP BY I.Id
--HAVING StatusId = 1 AND RefundAmount = 0
) I
WHERE I.StatusId = 1 AND I.RefundAmount = 0
The query works fine. But I’d like to know if somebody has already encountered this, and found a fix. I’m using MySQL 5.0.
Thanks
WHEREclause is used to filter data on the common attributes and expressions.HAVINGclause is used to filter data after groupping had been performed and it’s arguments should be either the ones of theGROUP BYclause, or expressions containing aggregate functions.It is also illegal to use the alias of the column in
WHERE,GROUP BYorHAVINGclauses, while it does works for theORDER BYclause.One option, as you’ve found, is to use a sub-query and then column references will work.
Another one is to duplicate the whole expression in the
HAVINGclause:EDIT: A closer look leaded to this question Using column alias in WHERE clause of MySQL query produces an error and to the MySQL documentation, that outlines that it is possible to use column aliases in
GROUP BY,HAVINGandORDER BYclauses if such aliases are quoted with backticks, like: