Skip to content

Instantly share code, notes, and snippets.

@stemwinder
Last active August 29, 2015 14:11
Show Gist options
  • Save stemwinder/8539991bd0c45f72c147 to your computer and use it in GitHub Desktop.
Save stemwinder/8539991bd0c45f72c147 to your computer and use it in GitHub Desktop.
SQL query that joins only one row from a relationship set using a derived table.
SELECT i.*, a.*
FROM inet_obdg_items i
JOIN inet_obdg_actions a ON a.item_id = i.id
JOIN (
SELECT derived_latest.item_id, MAX(derived_latest.id) AS latest_action_id
FROM inet_obdg_actions derived_latest
WHERE derived_latest.deleted_at IS NULL
GROUP BY derived_latest.item_id
) z ON z.item_id = a.item_id
AND z.latest_action_id = a.id
WHERE a.account_id = 424
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment