简体   繁体   English

在WHERE子句中使用列别名

[英]Using column aliases in a WHERE clause

A WHERE is evaluated first before a SELECT column list. 首先在SELECT列列表之前评估WHERE As a result the following: 结果是:

SELECT l_n AS last_name FROM contacts WHERE last_name > 'J';

can not work. 无法工作。
The following will work: 以下将起作用:

SELECT * FROM (SELECT l_n AS last_name FROM contacts) tmp WHERE last_name > 'J';

My question is: Is this also classified as a subquery? 我的问题是:这也归类为子查询吗? And if yes, if I wanted to avoid using subqueries is there another alternative for this? 如果是的话,如果我想避免使用子查询,是否还有另一种选择呢?

To the question, " Is this also classified as a subquery", the answer is yes. 对于“这是否也被归为子查询”这个问题,答案是肯定的。 To the question of avoiding subqueries, the easiest way is to use the actual column name in the where clause of your query. 对于避免子查询的问题,最简单的方法是在查询的where子句中使用实际的列名。

Yes, here is... 是的,这是...

SELECT l_n AS last_name FROM contacts HAVING last_name > 'J';

Keep in my that your query is gonna bring all the results (full scan) and then filter by your criteria on the Having clause. 请记住,您的查询将带来所有结果(全面扫描),然后根据Haveing子句中的条件进行过滤。

You should use a subquery if you concerned about performance. 如果您担心性能,则应使用子查询。 Or rather: 更确切地说:

SELECT l_n AS last_name FROM contacts HAVING l_n > 'J';

[EDIT] [编辑]

Hey mate, yes it works with no aggregation function. 嗨,老兄,是的,它没有聚合功能。 here is a example: 这是一个例子:

mysql> select * from blah;
+----+---------+
| id | name    |
+----+---------+
|  1 | renato  |
|  2 | rodrigo |
+----+---------+
2 rows in set (0.00 sec)


mysql> select id as a1, name as a2 from blah having a1 > 1;
+----+---------+
| a1 | a2      |
+----+---------+
|  2 | rodrigo |
+----+---------+
1 row in set (0.00 sec)

My database is a 5.5.29-0ubuntu0.12.04.2. 我的数据库是5.5.29-0ubuntu0.12.04.2。

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

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