1

I have a problem with the WHERE CLAUSE in mysql query. I want to filter data from a column that I directly defined. this is my example table (named MEMBER) :

++++++++++++++++
title | name   |
++++++++++++++++
leaf  | andro  |
moon  | sheila |
rocks | sarah  |

I run this query :

SELECT *, IF( title = "moon", "fly","on earth") AS status FROM MEMBER;

and the result :

+++++++++++++++++++++++++
title | name   | status |
+++++++++++++++++++++++++
leaf  | andro  |on earth|
moon  | sheila |fly     |
rocks | sarah  |on earth|

But why when I added a WHERE CLAUSE to filter the status column at the end of the query it returns an error? this is the query:

SELECT *, IF( title = "moon", "fly","on earth") AS status 
FROM MEMBER 
WHERE status = "fly";

the error message is : #1054 - Unknown column 'status' in 'where clause'
the 'directly defined' column that i mean is status column, it's not exist in the table but i created/defined it in the query.
I have tried to create status column in the table and it has null value, so when i run the second query (that containing WHERE CLAUSE), it would returns zero result.
i know another way to filter the data, i can use this query :

SELECT *, IF( title = "moon", "fly","on earth") AS status 
FROM MEMBER 
WHERE title = "moon";

but I can't do the filter by using that query in my case. I have to filter the status column.
Please don't see this question as a fool question, because this is the case that i have. So, anybody has the alternatives?

Oki Erie Rinaldi
  • 1,835
  • 1
  • 22
  • 31

2 Answers2

2

With sub-query:

SELECT * FROM
(
 SELECT *, IF( title = "moon", "fly","on earth") AS status  
 FROM MEMBER 
) sq 
WHERE status = "fly";

SQL Fiddle

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
1

Use the HAVING clause to set a condition on status field. The field status was aggregated outside of the table itself and hence, WHERE can do nothing.

SELECT 
    *, 
    IF( title = "moon", "fly","on earth") AS status 
FROM MEMBER 
HAVING status = "fly";
Community
  • 1
  • 1
hjpotter92
  • 78,589
  • 36
  • 144
  • 183