MYSQL Only limit results from left table, but show all results from right table

I am setting up a database which stores posts for a website called “news”. Each news post can have some (0-255) media(s) stored with it. I can get all the data like so:

SELECT * 
FROM news 
LEFT JOIN media ON news.id = news_id

Which returns:

news.idtitlecreatedmedia.idnews_idfilename
1Title1NULLNULLNULL
2Title2NULLNULLNULL
3Title3NULLNULLNULL
4Title4NULLNULLNULL
5Title515media1.png
5Title525media2.png

Notice that news.id = 5 shows up for twice since it has two images associated with it.

My goal is to get the latest 3 posts like so

SELECT * 
FROM news 
LEFT JOIN media ON news.id = news_id 
ORDER BY created DESC 
LIMIT 3

Which returns:

news.idtitlecreatedmedia.idnews_idfilename
5Title525media2.png
5Title515media1.png
4Title4NULLNULLNULL

However I would like it to return all the posts with ids 5, 4, and 3 along with all their media like so:

news.idtitlecreatedmedia.idnews_idfilename
5Title525media2.png
5Title515media1.png
4Title4NULLNULLNULL
3Title3NULLNULLNULL

Is this possible with MySql or is there some other database organization that can accomplish this? Basically I would like to only limit the results from the LEFT table and let the “repeats” show up so I can still get all the RIGHT table data. I am using PHP prepared statements to make these MYSQL queries so I may not be able to use subquery but I am not sure.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Select from a subquery that gets the last 3 posts, rather than the whole table.

SELECT *
FROM (
    SELECT *
    FROM news
    ORDER BY created DESC
    LIMIT 3
) AS news
LEFT JOIN media ON news.id = news_id


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x