问题
In the sql below I have the last 5 posts. But sometimes these posts are from the same author. I want to select the last 5 but just one per author.
SELECT `e` . * ,
`f`.`title` AS `feedTitle` ,
`f`.`url` AS `feedUrl` ,
`a`.`id` AS `authorId` ,
`a`.`name` AS `authorName` ,
`a`.`about` AS `authorAbout`
FROM `feed_entries` AS `e`
INNER JOIN `feeds` AS `f` ON e.feed_id = f.id
INNER JOIN `entries_categories` AS `ec` ON ec.entry_id = e.id
INNER JOIN `categories` AS `c` ON ec.category_id = c.id
INNER JOIN `authors` AS `a` ON e.author_id = a.id
GROUP BY `e`.`id`
ORDER BY `e`.`date` DESC
LIMIT 5
EDITED
I've ended up with it:
SELECT a.id, e.date, e.title, a.name
FROM feed_entries e, authors a
WHERE e.author_id =a.id
ORDER BY e.date DESC
LIMIT 5
In this query, how can I get just one post for each author?
回答1:
What about
select a.id, a.name, e.date, e.titulo
from feed_entries e
inner join authors a
on e.author_id = a.id
-- Get the most recent feed_entry
and e.date = (select max(e1.date) from feed_entries e1 where e1.author_id = a.id)
order by e.date desc
I haven't tested that but it could work.
回答2:
I've got the anwser here: DISTINCT a column in a database
I've did some modifications and works fine.
SELECT * FROM (
SELECT `e` . * ,
`f`.`title` AS `feedTitle` ,
`f`.`url` AS `feedUrl` ,
`a`.`id` AS `authorId` ,
`a`.`name` AS `authorName` ,
`a`.`about` AS `authorAbout`
FROM `feed_entries` AS `e`
INNER JOIN `feeds` AS `f` ON e.feed_id = f.id
INNER JOIN `entries_categories` AS `ec` ON ec.entry_id = e.id
INNER JOIN `categories` AS `c` ON ec.category_id = c.id
INNER JOIN `authors` AS `a` ON e.author_id = a.id
GROUP BY `e`.`id`
ORDER BY `e`.`date` DESC
) t GROUP BY author_id ORDER BY date DESC
LIMIT 5
回答3:
You could try something along these lines (not tested yet):
SELECT `e` . * , `f`.`title` AS `feedTitle` , `f`.`url` AS `feedUrl` , `a`.`id` AS `authorId` , `a`.`name` AS `authorName` , `a`.`about` AS `authorAbout`
FROM `feed_entries` AS `e`
INNER JOIN `feeds` AS `f` ON e.feed_id = f.id
INNER JOIN `entries_categories` AS `ec` ON ec.entry_id = e.id
INNER JOIN `categories` AS `c` ON ec.category_id = c.id
INNER JOIN `authors` AS `a` ON e.author_id = a.id
INNER JOIN ( SELECT TOP 1 entry_id, author_id
FROM feed_entries
GROUP BY author_id
ORDER BY date DESC) as top_article
ON (a.id = top_article.author_id)
GROUP BY `e`.`id`
ORDER BY `e`.`date` DESC
LIMIT 5
来源:https://stackoverflow.com/questions/3886070/how-to-change-this-sql-so-that-i-can-get-one-post-from-each-author