简体   繁体   English

在MySql的内部选择中使用列别名

[英]Using column alias in inner select in MySql

It seems that I can't alias a column and use it in the inner select in MySql. 看来我不能为一列加上别名并在MySql的内部select中使用它。
How do I do the following in MySql for example? 例如,如何在MySql中执行以下操作?

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! MySql无法识别M_ID别名!

My table structure: 我的表结构:

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

Either just use the original column name - this should work as long as the MANAGERS table does not have an ID column: 要么只使用原始的列名-只要MANAGERS表没有ID列,这就应该起作用:

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. 列别名只能在ORDER BYGROUP BYHAVING子句中使用。 Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. 标准SQL不允许您在WHERE子句中引用列别名。 This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined. 之所以施加此限制,是因为执行WHERE代码时,可能尚未确定列值。

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. 即使在这种简单的情况下,我也会假设MySQL查询优化器可以在执行计划中找到一种简单的方法。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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