简体   繁体   中英

Select all from table where the rows has the highest id of all those with the same foreign keys

So I have a posts table with a author_id foreign key and a published status (bool).

I want to select all the most recent (highest id) published posts for an author (all those with the same author_id foreign id).

Right now I can get the highest for a group of foreign keys

SELECT * FROM Posts WHERE id = (SELECT MAX(id) FROM Posts WHERE  published = 1 AND author_id = 5); 

But this only returns the highest id for a given foreign key. How would I write this to return all the posts with the highest id in their foreign key group?

Any advice is appreciated. Thanks

EDIT: Had it tagged with sql-server and mysql. It's mysql. Sorry about that

EDIT: Some asked for clarity Here is a sample of what I'm looking for: id body author_id published 1 Top 10... 1 1 2 Breaking... 1 1 3 New Report.. 3 1 4 Can Sunscreen... 3 1 5 Dow down... 2 1 6 Heart Warming... 2 1 7 Next time... 1 1 8 New study... 3 0

So what i want to do is grab the posts with ids 4, 6, and 7 because 4 is the most recent (highest id) for author 3, 6 is the most recent for author 2 and 7 is the most recent for author 1. I also have the conditional of published which is why we don't grab 8 because it is 0.

4 Can Sunscreen... 3 1 6 Heart Warming... 2 1 7 Next time... 1 1

Answered: With a slight tweak to Igor Quirino answer by adding an IN instead of =, i think the following works:

SELECT * FROM Posts WHERE id IN (SELECT MAX(id) FROM Posts WHERE published = 1 GROUP BY author_id);

You need to do this:

SELECT * FROM Posts WHERE id IN (SELECT MAX(id) FROM Posts WHERE published = 1 GROUP BY author_id); 

Happy to Help.

If you want the most recent posts for an author, use ORDER BY and LIMIT . For instance, to get the 10 most recent posts for author 5:

SELECT p.*
FROM Posts p
WHERE p.author_id = 5
ORDER BY p.id DESC
LIMIT 10;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM