I have the following tables:
Posts:
| id (pk) | title |
|---------|---------|
| 1 | title 1 |
| 2 | title 2 |
Images:
| id (pk) | post_id (fk) | display_order | image_path |
|---------|--------------|---------------|------------|
| 1 | 1 | 1 | image1.jpg |
| 2 | 1 | 2 | image2.jpg |
| 3 | 1 | 0 | image3.jpg |
| 4 | 2 | 1 | image4.jpg |
| 5 | 2 | 1 | image5.jpg |
| 6 | 2 | 2 | image6.jpg |
I’d like to retrieve a list of posts each containing the first item in images based on display_order
.
The desired result would be like this:
| id | title | thumb_path |
|----|---------|------------|
| 1 | title 1 | image3.jpg |
| 2 | title 2 | image4.jpg |
How can I do this?
2
Answers
You can get only one row on a related table using a lateral join. For example:
A classic PostgreSQL solution is a
distinct on
clause.The first row for each
post_id
is defined with theorder by
The rest is a simple
join