复杂的联接查询,联接具有多个分组依据的3个表

时间:2018-07-14 13:42:36

标签: sql postgresql

我有3张桌子:

推文:

CREATE TABLE tweets (
    text_content    VARCHAR(280) not null,
    username        VARCHAR(50) not null,
    timestamp       TIMESTAMP not null DEFAULT current_timestamp,
    id              UUID not null DEFAULT uuid_generate_v4(),
    CONSTRAINT      tweets_pk PRIMARY KEY (id)
);

喜欢:

CREATE TABLE likes (
    username        VARCHAR(50) not null,
    timestamp       TIMESTAMP not null default current_timestamp,
    post_id         UUID not null,
    CONSTRAINT      likes_pk PRIMARY KEY (username, post_id),
    CONSTRAINT      likes_post_id_fk FOREIGN KEY (post_id) REFERENCES tweets(id)
);

和转发

CREATE TABLE retweets (
    username        VARCHAR(50) not null,
    timestamp       TIMESTAMP not null default current_timestamp,
    post_id         UUID not null,
    CONSTRAINT      retweets_pk PRIMARY KEY (username, post_id),
    CONSTRAINT      retweets_post_id_fk FOREIGN KEY (post_id) REFERENCES tweets(id)
);

我需要一个查询,该查询将选择所有推文,以及它们所拥有的喜欢和转发的数量。
我确实写了一个有效的查询,但是我认为它过于复杂了,很想听听更简单的解决方案!

1 个答案:

答案 0 :(得分:1)

您想在加入之前 进行汇总。假设join键是post_id

select t.*, l.likes, r.retweets
from tweets t left join
     (select post_id, count(*) as likes
      from likes
      group by post_id
     ) l
     on l.post_id = t.id left join
     (select post_id, count(*) as retweets
      from retweets
      group by post_id
     ) r
     on r.post_id = t.id;