源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

mysql "group by"与"order by"的研究--分类中最新的内容

  • 时间:2022-03-10 21:06 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:mysql "group by"与"order by"的研究--分类中最新的内容
这两天让一个数据查询难了。主要是对group by 理解的不够深入。才出现这样的情况 这种需求,我想很多人都遇到过。下面是我模拟我的内容表
[url=http://atim.cn/read.php/attachment.php?fid=86][img]http://files.jb51.net/upload/201006/20100621123043781.gif[/img] [/url] 我现在需要取出每个分类中最新的内容
[url=http://atim.cn/read.php/attachment.php?fid=87][img]http://files.jb51.net/upload/201006/20100621123043252.gif[/img] [/url] 明显。这不是我想要的数据,原因是msyql已经的执行顺序是 [url=http://atim.cn/read.php/attachment.php?fid=86][img]http://files.jb51.net/upload/201006/20100621123043781.gif[/img] [/url] 到group by时就得到了根据category_id分出来的多个小组 [url=http://atim.cn/read.php/attachment.php?fid=88][img]http://files.jb51.net/upload/201006/20100621123043898.gif[/img] [/url] [url=http://atim.cn/read.php/attachment.php?fid=89][img]http://files.jb51.net/upload/201006/20100621123043749.gif[/img] [/url] 到了select的时候,只从上面的每个组里取第一条信息结果会如下 [url=http://atim.cn/read.php/attachment.php?fid=90][img]http://files.jb51.net/upload/201006/20100621123043526.gif[/img] [/url] 即使order by也只是从上面的结果里进行排序。并不是每个分类的最新信息。 回到我的目的上 --分类中最新的信息 根据上面的分析,group by到select时只取到分组里的第一条信息。有两个解决方法 1,where+group by(对小组进行排序) 2,从form返回的数据下手脚(即用子查询) [b]由where+group by的解决方法[/b] 对group by里的小组进行排序的函数我只查到group_concat()可以进行排序,但group_concat的作用是将小组里的字段里的值进行串联起来。
select group_concat(id order by `date` desc) from `test` group by category_id
[url=http://atim.cn/read.php/attachment.php?fid=91][img]http://files.jb51.net/upload/201006/20100621123043254.gif[/img] [/url] 再改进一下
select * from `test` where id in(select SUBSTRING_INDEX(group_concat(id order by `date` desc),',',1) from `test` group by category_id ) order by `date` desc
[url=http://atim.cn/read.php/attachment.php?fid=92][img]http://files.jb51.net/upload/201006/20100621123043887.gif[/img] [/url] [b]子查询解决方案[/b]
select * from (select * from `test` order by `date` desc) `temp`  group by category_id order by `date` desc
[url=http://atim.cn/read.php/attachment.php?fid=92][img]http://files.jb51.net/upload/201006/20100621123043887.gif[/img] [/url] 
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部