Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 复杂的联接查询,使用多个group BY联接3个表_Sql_Postgresql - Fatal编程技术网

Sql 复杂的联接查询,使用多个group BY联接3个表

Sql 复杂的联接查询,使用多个group BY联接3个表,sql,postgresql,Sql,Postgresql,我有三张桌子: 推特: 喜欢: 和转发 我需要一个查询,该查询将选择所有推文,以及他们的喜欢和转发量。 我确实设法写了一个有效的查询,但我认为我把它复杂化了,我希望听到更简单的解决方案 您希望在加入之前进行聚合。假设join键是post\u id: select t.*, l.likes, r.retweets from tweets t left join (select post_id, count(*) as likes from likes group

我有三张桌子:

推特: 喜欢: 和转发 我需要一个查询,该查询将选择所有推文,以及他们的喜欢和转发量。
我确实设法写了一个有效的查询,但我认为我把它复杂化了,我希望听到更简单的解决方案

您希望在加入之前进行聚合。假设
join
键是
post\u 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;

示例数据和所需结果将有所帮助。请发布您的代码,这将是帮助您改进方法的有用起点。非常感谢
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)
);
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;