0

我有一个用户表,就像(短路):

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

但这会产生奇怪的结果。

感谢您的任何意见!

4

1 回答 1

1

这可能是你想要的:

SELECT u.username, p.postsCount, recomm.recommCount, recomm.likesCount
FROM users u 
JOIN
 (
   SELECT author_id, COUNT(*) AS postsCount
   GROUP BY author_id
 )  AS p
ON u.id = p.author_id
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
于 2013-09-16T11:33:44.297 回答