开发者社区 问答 正文

Django ORM 查询每个用户的最后一条评论

Model定义伪代码

class Comment():
   user_id
   text
   create_time

查询user_id in [1,2,3,4,5]中的的最后一条评论,用Django ORM怎么写? 如果不行的话,SQL怎么写呢

展开
收起
a123456678 2016-07-01 14:43:26 3439 分享 版权
1 条回答
写回答
取消 提交回答
  • 如果你的comment_id是自增长的话

    select * from comments where comment_id in (
        select max(comment_id) as comment_id from comments
        where user_id in (1, 2, 3, 4, 5)
        group by user_id
    )
    如果comment_id不是自增长,create_time也可以将就,同一用户应该不会出现create_time重复的情况
    
    select * from comments where create_time in (
        select max(create_time) as create_time from comments
        where user_id in (1, 2, 3, 4, 5)
        group by user_id
    ) and user_id in (1, 2, 3, 4, 5)
    2019-07-17 19:50:01
    赞同 展开评论
问答分类:
问答地址: