1

我对WHERE CLAUSEin mysql 查询有疑问。我想从我直接定义的列中过滤数据。这是我的示例表(名为 MEMBER):

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

我运行这个查询:

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

结果:

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

但是为什么当我在查询末尾添加一个WHERE CLAUSE过滤status列时它会返回错误?这是查询:

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

错误消息是: #1054 - Unknown column 'status' in 'where clause'
我的意思是“直接定义”列status,它在表中不存在,但我在查询中创建/定义了它。
我试图status在表中创建列并且它具有空值,所以当我运行第二个查询(包含WHERE CLAUSE)时,它会返回zero result.
我知道另一种过滤数据的方法,我可以使用这个查询:

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

但在我的情况下,我无法使用该查询进行过滤。我必须过滤status列。
请不要将此问题视为愚蠢的问题,因为我就是这种情况。那么,有人有替代品吗?

4

2 回答 2

2

使用子查询:

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

SQL小提琴

于 2013-10-21T01:49:16.707 回答
1

使用该HAVING子句status在字段上设置条件。该字段status在表本身之外聚合,因此WHERE无能为力。

SELECT 
    *, 
    IF( title = "moon", "fly","on earth") AS status 
FROM MEMBER 
HAVING status = "fly";
于 2013-10-21T01:38:10.110 回答