Postgresql Join on Select 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18969479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:07:15  来源:igfitidea点击:

Postgresql Join on Select Statement

sqlpostgresqljoin

提问by Stanley Cup Phil

I want to do a join on a SelectStatement in Postgresql, but I am having issues

我想加入SelectPostgresql 中的语句,但我遇到了问题

SELECT 
    s.sessionid, sp.lang 
FROM 
    sessions s
INNER JOIN 
    pages sp 
ON 
    sp.sessionid =  s.sessionid 
INNER JOIN
(
    SELECT 
        max(sessionid)
    FROM 
        sessions
    AS 
        maxSession
)
ON 
    maxSession = s.sessionid
WHERE 
    --Where condition

I get the following error: ERROR: subquery in FROM must have an alias

我收到以下错误:错误:FROM 中的子查询必须有一个别名

LINE 6: (
        ^
HINT:  For example, FROM (SELECT ...) [AS] foo.

If I add the FROM

如果我添加 FROM

FROM
(
    SELECT max(sessionid)
    FROM sessions
)
AS maxSession

I get another error

我收到另一个错误

ERROR:  syntax error at or near "FROM"
LINE 7:  FROM

Ideas?

想法?

回答by Twelfth

You are close.

你很近。

  INNER JOIN
 (
  SELECT 
    max(sessionid) as 'maxSession'
   FROM 
   sessions        
) maxSession
ON 
maxSession.maxSession = s.sessionid

Any time you refer to a query as a table, you need to give it an alias...alias goes right after the entire subquery, not in the subquery itself.

任何时候将查询称为表时,都需要给它一个别名...别名紧跟在整个子查询之后,而不是在子查询本身中。