我有一个用户表,就像(短路):
id (BIGINT)
username (VARCHAR)
recommendedByUserId (BIGINT)
在recommendedByUserId
推荐人的ID中存储,这是users.id
推荐人的-value。这是有效的:
SELECT u.username, recomm.recommCount, recomm.likesCount
FROM users u
INNER JOIN
(
SELECT recommendedByUserId as rid, COUNT(*) as recommCount, SUM(u.likes) as likesCount
FROM users u
GROUP BY recommendedByUserId
) recomm on recomm.rid = u.id
ORDER BY recomm.recommCount DESC
现在我还需要计算一个用户有多少个帖子被另一个用户推荐过,并在推荐者上总结出来。我以为我可以这样做:
SELECT u.username, recomm.recommCount, recomm.likesCount, recomm.postsCount
FROM users u
INNER JOIN
(
SELECT recommendedByUserId as rid, COUNT(*) as recommCount, SUM(u.likes) as likesCount, COUNT(posts.id) AS postsCount
FROM users u
INNER JOIN posts ON u.id = posts.author_id
GROUP BY recommendedByUserId
) recomm on recomm.rid = u.id
ORDER BY recomm.recommCount DESC
但这会产生奇怪的结果。
感谢您的任何意见!