How to change this SQL so that I can get one post from each author?

让人想犯罪 __ 提交于 2020-01-07 04:14:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!