16

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

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

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

If I add the FROM

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

I get another error

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

Ideas?

2
  • 2
    remove the ALIAS on the subquery. it should be outside. ( SELECT max(sessionid) maxSession FROM sessions ) AS maxSession ON maxSession.maxSession = s.sessionid Commented Sep 23, 2013 at 21:49
  • alias is manatadory Commented Oct 30, 2021 at 23:44

1 Answer 1

22

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.

Sign up to request clarification or add additional context in comments.

2 Comments

one more missing, you need to give an alias for max(sessionid)
ah yes, sloppy on my part. fixxed...and just noticed you got to the error in a comment before my answer was posted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.