MySQL指望连接表

时间:2013-09-16 11:06:01

标签: mysql sql join

我有一个像(短)的用户表:

id (BIGINT)
username (VARCHAR)
recommendedByUserId (BIGINT)

recommendedByUserId中,存储推荐者的ID,即推荐者的users.id - 值。这是有效的:

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

但这会产生奇怪的结果。

感谢您的任何意见!

1 个答案:

答案 0 :(得分: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