我将表格命名为帖子
|id|user_id|title|description|
喜欢这样的表
|id|user_id|post_id|
这是我的sql代码
select count(likes.id) as like_count, posts.* from `posts` left join
`likes` on `likes`.`post_id` = `posts`.`id` where `posts`.`status` = 'A'
group by `posts`.`id` order by `like_count` desc LIMIT 6
结果如下
|like_count | id | user_id | title | description |
---------------------------------------------------
17 | 723 | 12 | ... | .... |
15 | 721 | 15 | ... | .... |
14 | 711 | 12 | ... | .... |
13 | 700 | 12 | ... | .... |
12 | 800 | 11 | ... | .... |
12 | 920 | 12 | ... | .... |
如您所见,user_id 12正在重复这一次,我只希望一个用户发布一条帖子。
有没有办法选择每个用户最喜欢的帖子,并让user_id不重复。
答案 0 :(得分:0)
我知道这可能不是最有效的解决方案,但这是我想到的第一个。不幸的是,MySQL不支持窗口函数,因此任务比使用窗口函数的方法更难,更不优雅。
每个用户最喜欢的帖子会重复user_id
,如果碰巧有多个帖子的数量相同且该数字对特定用户来说最大:
select
user_likes.post_user_id,
user_likes.like_count,
p.id as post_id,
p.title,
p.description
from (
select
p.user_id as post_user_id,
MAX(l.like_count) as like_count
from posts p
inner join (select post_id, count(*) as like_count from likes group by post_id) l on p.id = l.post_id
group by p.user_id
) user_likes
inner join (select post_id, count(*) as like_count from likes group by post_id) l on user_likes.like_count = l.like_count
inner join posts p on l.post_id = p.id
如果你真的需要每个用户一行,那么如果不同帖子的喜欢数量相关,你需要选择一个策略来只检索其中一个。例如,您可以通过在post_id
上添加分组并获取其值min()
并加入post表来检索其标题和说明,从而获取较旧的那个。
在这种情况下,上述脚本的修改如下所示:
select
most_liked_post.post_user_id,
most_liked_post.like_count,
most_liked_post.post_id,
p.title,
p.description
from (
select
user_likes.post_user_id,
user_likes.like_count,
MIN(l.post_id) AS post_id
from (
select
p.user_id as post_user_id,
MAX(l.like_count) as like_count
from posts p
inner join (select post_id, count(*) as like_count from likes group by post_id) l on p.id = l.post_id
group by p.user_id
) user_likes
inner join (select post_id, count(*) as like_count from likes group by post_id) l on user_likes.like_count = l.like_count
group by user_likes.post_user_id, user_likes.like_count
) most_liked_post
inner join posts p on most_liked_post.post_id = p.id