Postgresql加入Select Statement

时间:2013-09-23 21:48:37

标签: sql postgresql join

我想在Postgresql中对Select语句进行连接,但是我遇到了问题

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

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

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

如果我添加FROM

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

我收到了另一个错误

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

想法?

1 个答案:

答案 0 :(得分:2)

你很亲密。

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

每当你将一个查询称为一个表时,你需要给它一个别名...别名就在整个子查询之后,而不是在子查询本身。