简体   繁体   中英

Mysql use column alias in where clause

I have a Mysql Query:

SELECT created_at as date FROM table

So I created an alias for the created_at column. Now I want to use this alias in my WHERE clause:

SELECT created_at as date FROM table WHERE date = 'xxxx-xx-xx'

This does not work. Mysql expects me to use the real column name. Is there any way to do it the way I want to?

Background: I am selecting records from several tables and unite them using UNION . All the tables have a date column but it's named different in every table. But I want to do WHERE on the united records and therefore I need to have always the same column name

If you absolutely have to use your alias as part of the selection criteria, then you need to use HAVING rather than WHERE

SELECT created_at as date FROM table HAVING date = 'xxxx-xx-xx'

But it's better to use the column name and WHERE because other people reading your code will find the meaning of WHERE more obvious than HAVING ; and it won't use your table indexes as efficiently either

You asked, "Is there any way to do it the way I want to?"

Yes, but it requires use of subquery, or a view.

SELECT date 
FROM  (SELECT created_at as date FROM table) B
WHERE date = 'xxxx-xx-xx'

With the case of a union...

SELECT * from (
Select col1, col2,col3 as date from A
union
select col1, col4,col5 from B) inlineView
WHERE date = 'somedate'

The problem you're running into is the order of operation within the database.

  1. FROM clause
  2. WHERE clause
  3. GROUP BY clause
  4. HAVING clause
  5. SELECT clause
  6. ORDER BY clause

(order taken from http://www.bennadel.com/blog/70-sql-query-order-of-operations.htm ) a different order was found MySQL Order of Operations?

so now I have to do some research to figure out which one is correct; or if it varies by RDBMS...

So the where clause is executed before the select is evaluated. Thus it doesn't know you aliased it yet. you can fool the compiler by making the data columns the way you want in the from clause by doing a subselect.

哪里对别名不起作用..最好使用table_name.column_namem,您可以在group by中使用列的别名。

  SELECT created_at  FROM table WHERE table.created_at = 'xxxx-xx-xx'  <--more readable, isn't it?

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