Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL greatest-n-per-group with relational table joins
    primarykey
    data
    text
    <p>I have 3 tables. image, categories, image_category.</p> <pre><code>image: id | title | imageURL categories: cat_id | cat_name image_category: image_id | cat_id </code></pre> <p>My current query to select all images in order newest to oldest is:</p> <pre class="lang-sql prettyprint-override"><code>SELECT image.id as ID, image.title as title, categories.cat_name as CAT FROM image_category LEFT JOIN image ON image_category.image_id = image.id INNER JOIN categories ON image_category.cat_id = categories.cat_id ORDER BY ID DESC </code></pre> <p>I would like to show the newest 4 images per category. The largest image.id are the newest images. </p> <p>For example. If I had 3 categories and 40 images in each category. I want to show the newest 4 images from each category. I will later be trying to show the next 4 per category after that and then the next 4 per category until there are no images left.</p> <p><a href="https://stackoverflow.com/questions/1442527/how-to-select-the-newest-four-items-per-category">This</a> solution seems like what im looking for.</p> <pre class="lang-sql prettyprint-override"><code>SELECT i1.* FROM item i1 LEFT OUTER JOIN item i2 ON (i1.category_id = i2.category_id AND i1.item_id &lt; i2.item_id) GROUP BY i1.item_id HAVING COUNT(*) &lt; 4 ORDER BY category_id, date_listed; </code></pre> <p>but I have a relational table connecting my image_id and category_id. Cant figure out how to implement this with that extra table join.</p> <p>Would appreciate help from an SQL guru.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload