我有5个表[结构]:
所有表都使用ID,在插入时递增。
这是我向用户显示图片流量的请求:
SELECT
m.id as mediaID,
COUNT(l.id) as likesCount,
COUNT(c.id) as commentsCount
FROM medias m
INNER JOIN follow f
ON f.follow = 'user_here' AND m.creatorID = f.following AND m.date < 'timestamp_here'
INNER JOIN users u
ON u.id = m.creatorID
LEFT JOIN likes x
ON m.id = x.mediaID AND x.senderID = 2
LEFT JOIN likes l
ON m.id = l.mediaID
LEFT JOIN comments c
ON m.id = c.mediaID
GROUP BY m.id
当有超过1条评论时,likesCount会获取commentsCount的值。当我不喜欢图片时,commentCount减少1条评论。所以,我真的不知道如何解决它......
答案 0 :(得分:1)
解决问题的简便方法是使用distinct
:
SELECT m.id as mediaID,
COUNT(DISTINCT l.id) as likesCount,
COUNT(DISTINCT c.id) as commentsCount
如果您有很多喜欢和评论,可以在加入或使用相关子查询之前更好地聚合。