根据其他 table 根据其他 table 获取一个 table 的计数和总和

Get count and sum of one table based on other table based on other table

我有 3 个 SQLite 表:

频道

channelId triad
1         1
2         1
3         0

视频

channelId videoId topic
1         xx      1
1         yy      0
2         pp      0
3         kk      1

评论

commentId replyId videoId sentiment
NULL      er41     xx      -3
clxpo     NULL     kk      0.05
clutz     NULL     yy      2.38
NULL      edg15    xx      1.7
clopq     NULL     pp      1
dkt2      NULL     kk      0.95

对于 triad = 1 的每个频道,我需要知道主题 = 1 的频道视频的情绪总和以及该频道的评论数。

键是:

channel.channelId = video.channelId

video.videoId = comment.videoId

最终结果应该是:

channelId sum(sentiment) count(number of comments) triad topic
1         -1,3           2                         1     1

如何链接这 3 个表以获得所需的结果?

这是一个简单的三向合并,通过一些过滤将其限制为 triadtopic 为 1 的行,在 channelid:

上分组
SELECT ch.channelid
     , sum(co.sentiment) AS sum_sentiment
     , count(*) AS num_comments
FROM channel AS ch
JOIN video AS v ON ch.channelid = v.channelid
JOIN comment AS co ON v.videoid = co.videoid
WHERE ch.triad = 1 AND v.topic = 1
GROUP BY ch.channelid
ORDER BY ch.channelid;

这给出了

channelid   sum_sentiment  num_comments
----------  -------------  ------------
1           -1.3           2           

如果您的表中有很多行,请使用 sqlite3 命令行工具的 .expert command to figure out what indexes should be added for an optimized execution plan