您的位置:首页 > 数据库

关于一个sql,六一儿童节快乐~

2012-06-01 14:06 260 查看
*查询test表中lotetype字段中有且只有两个相同的记录,且这两条记录中的date_time时间间隔为十分钟,取其中的一条作为结果输出。

表:

CREATE TABLE `test` (
`id` varchar(20) COLLATE utf8_swedish_ci,
`lotetype` varchar(20) COLLATE utf8_swedish_ci,
`date_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY `un_id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=331 DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci;


数据:



查询SQL:

select group_concat(distinct t1.lotetype), t1.id,t1.date_time
from
(select t.id,t.lotetype,t.date_time from test t ,(select lotetype, count(*) as c from test group by lotetype) tc where tc.c=2 and t.lotetype = tc.lotetype) t1 ,
(select t.id,t.lotetype,t.date_time from test t ,(select lotetype, count(*) as c from test group by lotetype) tc where tc.c=2 and t.lotetype = tc.lotetype) t2
where  t1.id!=t2.id
and 		abs(TIME_TO_SEC(timediff( t1.date_time,t2.date_time)) div 60)<10
and 		t1.lotetype=t2.lotetype
group by t1.lotetype;


查询结果:



说明:

1. group_concat函数结合group by去除group_concat包含的字段重复项。

2.取lotetype字段总数为2,关键用到group by分组。

3.时间撮是10分钟用到几个函数,abs(TIME_TO_SEC(timediff( t1.date_time,t2.date_time)) div 60) ,abs取正数,TIME_TO_SEC结果是秒钟,div除法函数

期待优化,这是一个面试题(同事面试遇到的,出这样的题目)。

太阳系 - http://blog.csdn.net/fellting
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐