简体   繁体   中英

SQL INNER JOIN does not see table alias

I'm having trouble with this SQL statement:

SELECT linkstable.date, (linkstable.count - x.count) 
FROM (SELECT .....) AS linkstable 
INNER JOIN linkstable AS x 
  ON linkstable.date = x.date+1 

It tells me that links table cannot be found although (SQL error 1146) there clearly is an alias to that select query. Can anybody tell me please how do I bypass this error?

You cannot alias an alias. If you want to join table to itself, repeat the select:

SELECT linkstable.date, (linkstable.count - x.count) 
FROM (SELECT .....) AS linkstable 
INNER JOIN (SELECT .....) AS x ON linkstable.date = x.date+1

If inner select is too cumbersome or you're running into performance issues insert its results into a temp table and use it in your main query.

You can't reference a subquery's alias in the FROM clause like that. However, if your database supports Common Table Expressions, you can use the WITH clause to accomplish the same thing:

WITH linkstable as (SELECT ...)
SELECT linkstable.date, (linkstable.count - x.count) 
FROM linkstable 
INNER JOIN linkstable AS x 
  ON linkstable.date = x.date+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