简体   繁体   中英

Why am I getting Unknown column in 'where clause' using a sub-query alias with MySQL?

I am getting an error message when I'm trying to give an Alias to a Sub-Query and then reference it in a Where clause: Unknown column 'point_status' in 'where clause'

SELECT goals.id, goals.status, 
ifnull((SELECT point_status FROM pts WHERE point_id = ?), goals.status) as point_status
FROM   goals
WHERE  goals.name = ? AND point_status > 1

I do not understand why it isn't allowing me to use this alias. Is it possible to use that alias somehow in the where clause by notmodifying the functionality of the Query?

You cannot use the Alias name in same select statement where clause. You can make it as a Sub-select and use the alias name in the outer query to filter the records.

select * from
(SELECT goals.id, goals.status, 
ifnull((SELECT point_status FROM pts WHERE point_id = ?), goals.status) as point_status
FROM   goals
WHERE  goals.name = ?)a
where point_status>1

It is not allowable to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed.

That means that you can't use aliases in a where clause.

Try replacing where with having .

You could use a subquery, or you might do the following instead (if using a subquery isn't convenient):

SELECT goals.id, goals.status
     , IFNULL((SELECT point_status FROM pts WHERE point_id = ?), goals.status) AS point_status
  FROM goals
 WHERE goals.name = ?
   AND IFNULL((SELECT point_status FROM pts WHERE point_id = ?), goals.status) > 1

Other possible solution:

CREATE VIEW vw_myView
AS
    SELECT goals.id, goals.status, 
ifnull((SELECT point_status FROM pts WHERE point_id = ?), goals.status) as point_status
FROM   goals

and then:

SELECT * from vw_MyView WHERE  goals.name = ? AND point_status > 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM