如何从另一个相关表中选择最后2个条目

时间:2019-04-11 06:26:25

标签: sql postgresql

我有一个查询,该查询根据他们在另一张表中的捐款总额来选择所有用户,并按其捐款总额进行排序。

但是我也想通过将每个用户的最后2条评论与一个空格连接在一起,选择评论类型为donation_comment的评论。并且还能够通过用户评论进行搜索。如果我指定comment_text包含“评论3”的位置,那么Sergey Brin仅显示1个条目。

我似乎无法弄清楚如何提取他们的最后评论并在此基础上添加条件。

结果就是这样

Array
    (
        [0] => stdClass Object
            (
                [id] => 2
                [username] => Sergey Brin
                [donation] => 500
                [last_comments] => comment four comment three
            )

        [1] => stdClass Object
            (
                [id] => 1
                [username] => Larry Page
                [donation] => 400
                [last_comments] => comment five comment two
            )
    )

这是我当前的查询

SELECT
    users.id,
    users.username,
    sum(donations.donation) as donation
from
    users
inner join donations
    on users.id = donations.user_id
where
    users.username like '%r%'
group by
    users.id,
    users.username
having
    sum(donations.donation) >= 400
order by
    donation desc

用户

id |   username   |
1     Larry Page
2     Sergey Brin

捐赠

id | user_id | donation |     date      |
1      1         100       2019-02-12
2      1         200       2019-02-13
3      2         500       2019-01-15
4      1         100       2019-04-10

user_comments

id | user_id |   comment_text   |        type        |
1       1        comment one       donation_comment
2       1        comment two       donation_comment
3       2        comment three     donation_comment
4       2        comment four      donation_comment 
5       1        comment five      donation_comment

2 个答案:

答案 0 :(得分:1)

我将从您的user_comments表中进行子查询,将每个user_id的评论数限制为2。然后您可以使用string_agg()来添加评论

尝试一下:

SELECT
    users.id,
    users.username,
    sum(donations.donation) as donation,
    string_agg(comment_text, ', ') as comments
from
    users
inner join donations
    on users.id = donations.user_id
inner join (
    SELECT* from user_comments
    group by user_id
    limit 2
    ) as last2_don on users.id = last2_don.user_id
where
    users.username like '%r%'
group by
    users.id,
    users.username
having
    sum(donations.donation) >= 400
order by
    donation desc

答案 1 :(得分:0)

横向连接是一种非常合理的方法:

select u.id, u.username,
       sum(d.donation) as donation,
       uc.comments_2
from users u inner join
     donations d
     on u.id = d.user_id left join lateral
     (select string_agg(comment_text, '; ') as comments_2
      from (select uc.*
            from user_comments uc
            where uc.user_id = u.id and
                  uc.type = 'donation_comment';
            order by uc.id desc
            limit 2
           ) c
      ) uc
      on 1=1
where u.username like '%r%'
group by u.id, u.username, uc.comments
having sum(d.donation) >= 400
order by sum(donation) desc;