mySql查询高于上次用户评论
我有下表:mySql查询高于上次用户评论,mysql,Mysql,我有下表: id post_id user_id to_user_id date time ---- ---------- -------- ------------ ------ 1 100 1 2 10:00 2 100 1 2 10:30 3 100 2 2 11:00 4 10
id post_id user_id to_user_id date time
---- ---------- -------- ------------ ------
1 100 1 2 10:00
2 100 1 2 10:30
3 100 2 2 11:00
4 100 5 2 11:30
5 100 8 2 11:45
6 105 10 50 09:00
7 105 2 50 09:30
8 105 11 50 11:00
9 105 30 50 11:30
10 105 32 50 11:45
在下表中,您可以看到用户_id 2对post 100和105有评论。
我只需要获得比他写的第一条评论高的每个帖子id的记录
因此,对于本例,结果将是post 100的记录4和5,以及post 105的记录8、9和10,因为4、5大于3(用户_id 2的第一条记录)
8,9,10比7大(用户2的第一个评论)
明确预期结果:
id post_id user_id to_user_id date time
可以使用subselect和聚合函数
select * from my_table
where ( post_id, date_time) > (select post_id, max( date_time)
from my_table where user_id =2
group y post_id);
或者如果元组版本无法正常工作,请尝试
select * from my_table as m
inner join (select post_id, max( date_time)
from my_table where user_id =2
group y post_id ) t on m.post_id = t.post_id
where m.date_time > t.date_time
我不明白这个问题!用户数2是什么意思?用户id=2,收件人id=2,或任何帖子的第二条评论?如果是最后一个,那么为什么不需要返回id=2,而id=4又是如何返回的呢?您没有id
150
的帖子。你的意思是105
?我想,你可以很容易地通过post\u id和MAX(user\u id)进行分组。检查我的答案。是的,对不起,编辑,所以你知道答案吗?不,我需要每个post_id,而不是所有的表格。我不需要最大值,因为id 4和7之后可能会有更多记录,我也需要获得它们。@GiladAdar。展示一个真实清晰的预期样本。。结果..高于第一个注释将意味着min(),而不是max()。
select * from my_table as m
inner join (select post_id, max( date_time)
from my_table where user_id =2
group y post_id ) t on m.post_id = t.post_id
where m.date_time > t.date_time