我有社交应用程序,比如说twitter,用户可以关注其他用户,也可以点评。
我需要获取的是用户的关注者以及每个关注者喜欢的最后2条评论的ID(如果有的话),以及使用MySQL的关注者关注者的数量。
以下是表格
表 user_follower
User_id follower_id
1 2
2 3
1 5
1 6
1 7
表 user_likes
comment_id User_id date
41 2 some_date
42 2 some_date
41 5 some_date
42 5 some_date
43 5 some_date
43 2 some_date
43 6 some_date
我们如何在单个mysql查询中执行此操作?
到目前为止,我能够得到关注者和关注者的关注者并跟随他们。
select uf.follower_id,
(select count(*) from user_followers uf1 where uf1.follower_id = uf.follower_id) as following_count,
(select count(*) from user_followers uf2 where uf2.user_id = uf.follower_id) as follower_count,
from user_followers uf
join users u on u.id = uf.follower_id
where uf.user_id = 1
我想要的是为每个关注者获取2个最新的comment_ids,即uf.follower_id。 如果在同一查询中不可能, 即使使用另一个查询,我也很好,因为它会在参数中传递follower_ids,但它应该为每个传递的ID提供2条最新评论..
答案 0 :(得分:0)
我认为这会奏效。我没有测试它,所以它可能有一些语法错误。鉴于此查询中使用的嵌套级别,我怀疑它对于非常大的数据集会表现不佳。
SELECT follower_id, num_followers, GROUP_CONCAT(comment_id)
FROM (
SELECT t.*,
@r := IF(@g = t.follower_id, @r+1, 1) RowNum,
@g := t.follower_id
FROM (select @g:=null) AS initvars
INNER JOIN (
SELECT followers.*, ul.comment_id
FROM (
SELECT
uf1.user_id,
uf1.follower_id,
COUNT(uf2.follower_id) AS num_followers
FROM user_follower uf1
LEFT JOIN user_follower uf2
ON uf1.follower_id = uf2.user_id
WHERE uf1.user_id = 1
GROUP BY uf1.user_id, uf1.follower_id
) AS followers
LEFT JOIN user_likes ul
ON followers.follower_id = ul.user_id
ORDER BY followers.follower_id ASC, comment_id DESC
) AS t
) AS final
WHERE RowNum < 3
GROUP BY follower_id, num_followers;
UPDATE 以下是使用不等式连接的其他查询 -
SELECT tmp.follower_id, COUNT(uf2.follower_id) AS num_followers, tmp.comments
FROM (
SELECT follower_id, GROUP_CONCAT(comment_id ORDER BY comment_id DESC) AS comments
FROM (
SELECT uf.follower_id, ul1.*
FROM user_follower uf
LEFT JOIN user_likes ul1
ON uf.follower_id = ul1.user_id
LEFT JOIN user_likes ul2
ON uf.follower_id = ul2.user_id
AND ul1.comment_id < ul2.comment_id
WHERE uf.user_id = 1
GROUP BY ul1.user_id, ul1.comment_id
HAVING COUNT(ul2.comment_id) < 2
) AS tmp
GROUP BY tmp.follower_id
) AS tmp
LEFT JOIN user_follower uf2
ON tmp.follower_id = uf2.user_id
GROUP BY tmp.follower_id