Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql Join on Select Statement

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?

like image 472
Soatl Avatar asked Sep 23 '13 21:09

Soatl


1 Answers

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.

like image 157
Twelfth Avatar answered Oct 19 '22 09:10

Twelfth