Search code examples
sqlsqliteleft-joinsql-limit

Implementing LIMIT against rows of single table while using LEFT JOIN


Given a fairly stereotypical scenario with an item table referenced by an images table holding multiple images for the same item, I'm trying to figure out how to retrieve a specific number of items, while collecting all of the image rows.

The setup is trivial, and looks like:

CREATE TABLE items (
  id  INTEGER PRIMARY KEY,
  ...
  ...
)

CREATE TABLE images (
  item_id INTEGER PRIMARY KEY,
  url     STRING,
  ...
  ...
)

LIMIT 20 clamps the maximum number of rows in the entire result set, and incidentally truncates mid-way through an item record.

I'm currently doing two queries, but besides being architecturally not at all ideal, it's practically proving quite awkward to coordinate (which makes a lot of sense since I'm definitely doing it wrong). I'm not finding any info on how to coordinate LIMIT with LEFT JOINs, so I thought I'd ask. Thanks!

NB. Similar questions to this do indeed exist, but are asking how to do things like retrieving eg the first (say) 5 images for each item. I'm looking to retrieve (say) 10 items and get all the images for each.


Solution

  • A query like:

    SELECT * FROM items ORDER BY ? LIMIT 10
    

    will return 10 rows (at most) from items.
    You need to provide the column(s) for the ORDER BY clause if you have some specific sorting condition in mind.
    If not then remove the ORDER BY clause, but in this case nothing guarantees the resultset that you will get.

    So all you have to do is LEFT join the above query to images:

    SELECT it.*, im.*
    FROM (SELECT * FROM items ORDER BY ? LIMIT 10) it
    LEFT JOIN images im
    ON im.item_id = it.id