如何更改此SQL以便我可以从每个作者获得一个帖子?

时间:2010-10-07 21:36:35

标签: sql mysql inner-join

在下面的sql中,我有最后5篇帖子。但有时这些帖子来自同一作者。我想选择最后5个,但每个作者只选一个。

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

我最终得到了它:

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

在此查询中,如何为每位作者只收到一篇帖子?

3 个答案:

答案 0 :(得分:1)

怎么样?
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

我没有测试过,但它可以工作。

答案 1 :(得分:0)

你可以尝试这些方面的东西(尚未测试):

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 

答案 2 :(得分:0)

我在这里得到了答案:DISTINCT a column in a database

我做了一些修改并且工作正常。

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