簡體   English   中英

如何從另一個相關表中選擇最后2個條目

[英]How to select the last 2 entries from another related table

我有一個查詢,該查詢根據他們在另一張表中的捐款總額來選擇所有用戶,並按其捐款總額對其進行排序。

但我也想通過將每個用戶的最后2條評論與一個空格連接在一起,選擇評論類型為donation_comment的評論。 並且還能夠通過用戶評論進行搜索。 如果我指定comment_text包含“注釋三”的位置,那么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

我將從您的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

橫向聯接是一種非常合理的方法:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM