• mysql里group by按照分组里的内容的排序


    得到一张表里按u_id分组,按count(id)排序,每个分组的pub_time最大的哪些记录,只取count(id)最大的4条

    select a.u_id,a.name,a.u_name,a.id,a.pub_time,b.cn from mb_resource a,
    (select max(pub_time) as pub_time,u_id,count(id) AS cn from mb_resource where auth_status = 2 GROUP BY u_id) b
    where a.u_id = b.u_id and a.pub_time = b.pub_time order by b.cn desc limit 4;

    子查询得到每个u_id分组的最新的pub_time,u_id,分组的里的总条数cn,
    外层自连接查询i,查询出分组总条数前四的信息(这里可以使用使用right join来减少外层的数据集)
    以上处理的原因是:
    1.mysql不支持组内排序。
    2.mysql不支持子查询limit。
    3.使用max(pub_time),而没有使用id,是因为在子查询里按分组来筛选max(pub_time),得到的id不应定是对应的那条数据的id


    得到一张表里按type分组,每组里hot最大的前7条,
    select a.name,a.id,a.type,a.hot from mb_resource a where a.auth_status=2
    and 7 > (select count(*) from mb_resource where auth_status=2 and type = a.type and hot > a.hot ) order by a.type desc, a.hot desc,a.pub_time desc

    以上处理的原因是:
    1.mysql不支持组内排序。
    2.mysql不支持子查询limit。
    3.没有使用分组,hot值的count不唯一,没有办法做第二次的排序取最大值。

  • 相关阅读:
    鼠标经过,显示悬浮DIV
    js 循环向上滚动
    Android 全局搜索条写成自定义控件-曹永思
    CYS-Sqlite数据导入工具
    启动Android App时,动态将Sqlite数据库文件导入到手机中类方法
    asp.net 多线程
    1.母版简单创建和使用
    class表与student表之间的关系
    02Del.ashx(删除班级)
    05StuList.aspx(学生列表)
  • 原文地址:https://www.cnblogs.com/kudosharry/p/3972291.html
Copyright © 2020-2023  润新知