tags:

views:

1075

answers:

2

hello,

It seems that I can't alias a column and use it in the inner select in MySql.

How do I do the following in MySql for example?

SELECT NAME,ID AS M_ID FROM EMPLOYEES WHERE EXISTS (SELECT 1 FROM MANAGERS WHERE MANAGERID = M_ID)

MySql would not recognize M_ID alias!

EMPLOYEES (ID,NAME) MANAGERS (MANAGERID,...)

Thanks

+1  A: 

What are you trying to do? Looks like it is to get all employees where there is a matching record in the manager table?

If that is the case couldn't you use

SELECT
  e.name
, e.id
FROM
  employees AS e
  inner join managers AS m ON (e.id = m.managerid)
Fermin
+4  A: 

Either just use the original column name - this should work as long as the MANAGERS table does not have an ID column:

SELECT NAME, ID AS M_ID 
FROM EMPLOYEES 
WHERE EXISTS (
    SELECT 1 
    FROM MANAGERS 
    WHERE MANAGERID = ID
)

Or better yet, use an alias for the tables:

SELECT e.NAME, e.ID AS M_ID 
FROM EMPLOYEES AS e
WHERE EXISTS (
    SELECT 1 
    FROM MANAGERS AS m
    WHERE m.MANAGERID = e.ID
)

Column aliases can only be used in the ORDER BY, GROUP BY and HAVING clauses. Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined.

By the way - using a subselect for the given problem might not be the best solution. Even though in this simple case I'd assume that the MySQL query optimizer can find a simple way in the execution plan.

Stefan Gehrig