mysql取出每个分组中最新的记录

mysql的gruopby分组功能没有排序功能,所以我们如果想取出某个分组下的最新记录是不太容易的,下面介绍两种方法,一种是通过子查询,一种是通过group_concat函数来实现。

一、表结构及数据插入

#表的结构 `test3`

CREATE TABLE IF NOT EXISTS `test3` (
`id` int(11) NOT NULL auto_increment,
`bid` int(11) NOT NULL,
`cid` int(11) NOT NULL,
`dtime` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

#转存表中的数据 `test3`

INSERT INTO `test3` (`id`, `bid`, `cid`, `dtime`) VALUES
(1, 1, 3, ’2014-03-18 16:00:00′),
(2, 1, 10, ’2014-03-18 17:00:00′),
(3, 2, 5, ’2014-03-18 18:00:00′),
(4, 2, 6, ’2014-03-18 19:00:00′),
(5, 1, 7, ’2014-03-18 20:00:00′);

二、通过子查询实现

1、sql语句

select * from(select * from test3 ORDER BY dtime DESC) as tempGROUP BY  bid ORDER BY dtime DESC;

三、通过group_concat函数

1、完整的语法
group_concat([DISTINCT] 要连接的字段 [Order BY ASC/DESC 排序字段] [Separator'分隔符'])

作用:将要连接的字段按照排序字段的顺序用分隔符连起来显示,默认分隔符是”,”。

2、sql语句

select substring_index(group_concat(id order by `dtime`desc),’,',1) as id, substring_index(group_concat(bid order by`dtime` desc),’,',1) as bid,substring_index(group_concat(cid orderby `dtime` desc),’,',1) as cid,substring_index(group_concat(dtimeorder by `dtime` desc),’,',1) as dtime from `test3` group bybid;

两上结果是一致的,虽然mysql自身的group by没有排序功能,但是通过自已的思考还是有办法的,写此作为备忘吧。

select * from (SELECT * FROM jcacard.v_inoroutrecord order by RecordDateTime desc) as temp
group by EmployName
having InOrOut = 1
order by RecordDateTime


  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值