zoukankan      html  css  js  c++  java
  • mysql group by组内排序

    mysql group by组内排序
     
    有数据表 comments
    ------------------------------------------------
    | id | newsID | comment | theTime |
    ------------------------------------------------
    | 1  |        1      |         aaa    |     11       |
    ------------------------------------------------
    | 2  |        1      |         bbb    |     12       |
    ------------------------------------------------
    | 3  |        2      |         ccc     |     12       |
    ------------------------------------------------
      www.2cto.com  
    newsID是新闻ID,每条新闻有多条评论comment,theTime是发表评论的时间
     
    现在想要查看每条新闻的最新一条评论:
     
    select * from comments group by newsID 显然不行
     
    select * from comments group by newsID order by theTime desc 是组外排序,也不行
     
    下面有两种方法可以实现:
      www.2cto.com  
    (1)
    selet tt.id,tt.newsID,tt.comment,tt.theTime from(  
    select id,newsID,comment,theTime from comments order by theTime desc) as tt group by newsID 
     
    (2)
    select id,newsID,comment,theTime from comments as tt group by id,newsID,comment,theTime having
     theTime=(select max(theTime) from comments where newsID=tt.newsID)
     
  • 相关阅读:
    if语句
    操作列表
    列表
    数据类型(不全)
    windows安装mysql
    hadr启动报错码
    db2主备hadr部署
    java--遍历字符个数
    java--装饰类
    java--继承&接口
  • 原文地址:https://www.cnblogs.com/yht520/p/3589639.html
Copyright © 2011-2022 走看看