Search code examples
sqlpostgresqlinner-join

PostgreSQL multiple join issue


Iam trying to create query with multiple JOINS, but Im receiving error message regarding syntax on second JOIN.

ERROR: syntax error at or near "INNER" LINE 19: INNER JOIN table2 AS jobinfo ON gaccess.... ^ SQL state: 42601 Character: 418

Can you help me what am I doing wrong?

SELECT
  access.id,
  access.user_id,
  access.device_id,
  access.origin,
  access.creation_date
FROM
  table1 access
  INNER JOIN (
    SELECT
      device_id,
      MAX (creation_date) AS creation_date
    FROM
      table1
    GROUP BY
      device_id
  ) gaccess ON access.device_id = gaccess.device_id
  AND access.creation_date = gaccess.creation_date;
  INNER JOIN 
    table2 AS jobinfo 
    ON gaccess.device_id = jobinfo.id

Solution

  • You have a type - before the last INNER JOIN there is ; - you need to remove it.

    SELECT access.id,
           access.user_id,
           access.device_id,
           access.origin,
           access.creation_date
    FROM table1 access
    INNER JOIN 
    (
        SELECT device_id
              ,MAX(creation_date) AS creation_date
        FROM table1
        GROUP BY device_id
    ) gaccess 
        ON access.device_id = gaccess.device_id
        AND access.creation_date = gaccess.creation_date
    INNER JOIN table2 AS jobinfo 
        ON gaccess.device_id = jobinfo.id;