PostgreSQL查询中的挑战(分组和有问题)

时间:2011-07-07 19:15:30

标签: sql postgresql greatest-n-per-group

我正在尝试创建一个查询,但我遇到了一些问题。我有两张桌子:

  • 用户(身份证,姓名,电子邮件)
  • 评论(id,uid,评论,日期,时间)

我正在尝试列出所有用户及其评论,这可以通过内部联接轻松完成。但是,我得到了每个用户的各种评论,因为我加入了结果。我只想要他们的最新评论。有任何想法吗? :)

5 个答案:

答案 0 :(得分:2)

这应该这样做:

select distinct on(u.name, u.id) *
from comments c, users u
where u.id=c.uid
order by u.name, u.id, c.date desc

答案 1 :(得分:1)

对于PostgreSQL 8.4 +:

SELECT x.*
  FROM (SELECT u.*, c.*,
               ROW_NUMBER() OVER (PARTITION BY u.id 
                                      ORDER BY c.date DESC, c.time DESC) AS rnk
          FROM USERS u
          JOIN COMMENTS c ON c.uid = u.id) x
 WHERE x.rnk = 1

答案 2 :(得分:0)

这可能有效:

编辑:

我将查询更新为:

SELECT u.id, u.name, u.email, t.id, t.uid, t.comment, t.date, t.time
FROM users u
LEFT OUTER JOIN
(
    select c.id, m.uid, c.comment, m.cdate, c.time
    from comments c
    right outer join 
        (
            select uid, max(date) as cdate
            from comments 
            group by uid
        ) as m
    ON c.cdate = m.cdate
) t
ON u.id = t.uid

答案 3 :(得分:0)

假设评论ID为自动增量,请找每个用户的最大值(最新评论)

SELECT u.id, u.name, u.email, c.id, c.uid, c.comment, c.date, c.time
FROM users u
JOIN comments c ON u.id = c.uid
JOIN 
    (
        select uid, max(id) id
        from comments
        group by uid
    ) as c2 ON c.id = c2.id AND c.uid = c2.uid

答案 4 :(得分:0)

OMG Ponies肯定有最好的答案,但这是另一种方法,没有任何扩展的数据库功能:

select

u.name,
c.comment,
c.comment_date_time

from users as u
left join comments as c
on c.uid = u.id
and
c.comment_date_time -
(
    select max(c2.comment_date_time)
    from comments as c2
    where c2.uid = u.id
) = 0

我已将此日期和时间列合并到此示例中的comment_date_time。