解决方案 »
- mysql表中字段该用哪种类型呢?--求大神
- 紧急急救!!phpmyadmin无法登陆mysql服务器!!
- 请真正了解mysql的朋友进来帮我解答一个问题?
- 请教一个触发器的问题
- ResultSet的getDate()方法从mysql的日期字段中取出的值为什么只有年月日,没有时分秒啊?
- windows下mysql触发器问题--delete
- 变量如何在条件语句中的应用如(WHERE 客户ID=1)怎样用变量@A代替‘客户ID=1’
- MYSQL数据导换出了大问题!急,在线等!
- 求一个SQL语句,条件如下
- Mysql存储过程调试方法
- Mysql二进制备份文件还原缓慢
- 求助 Mariadb 配置集群后,无法启动
+----+------+---------+---------------------+
| id | code | content | ctime |
+----+------+---------+---------------------+
| 2 | a | on | 2014-07-04 21:17:53 |
| 3 | a | abc | 2014-07-04 21:18:53 |
| 4 | a | off | 2014-07-04 21:19:53 |
| 5 | b | on | 2014-07-04 21:20:53 |
| 6 | b | abc | 2014-07-04 21:22:53 |
| 7 | b | off | 2014-07-04 21:29:53 |
| 8 | a | on | 2014-07-04 21:34:53 |
| 9 | a | abc | 2014-07-04 21:36:53 |
| 10 | a | off | 2014-07-04 21:45:53 |
| 11 | b | on | 2014-07-04 22:12:53 |
| 13 | b | abc | 2014-07-04 22:18:53 |
| 14 | b | off | 2014-07-04 22:19:53 |
+----+------+---------+---------------------+
12 rows in set (0.00 sec)mysql> select `code`,sum(k) from (
-> select `code`,
-> TIMESTAMPDIFF(MINUTE,(select max(ctime) from hp_report where `code`=a.code and ctime<a.ctime),ctime) as k
-> from hp_report a
-> where content='off'
-> ) t
-> group by `code`;
+------+--------+
| code | sum(k) |
+------+--------+
| a | 10 |
| b | 8 |
+------+--------+
2 rows in set (0.00 sec)mysql>
SELECT a.`code`,a.`ctime`,MIN(a1.`ctime`),TIMEDIFF(MIN(a1.`ctime`),a.`ctime`) AS ss FROM `hp_report` A LEFT JOIN `hp_report` A1
ON a1.`code`=a.`code` AND a1.`ctime`>a.`ctime`
WHERE A.`content`='on' AND A1.`content`='off' GROUP BY a.`code`,a.`ctime`) a GROUP BY a.`code`
谢谢WWWWA你的sql语句对了。但是由于我的表中有百万条记录,所以比较慢,能不能优化下。非常感谢!!!
set @on := 0,@off := 0;
select m.`code`,sum(m.mtime)mtime from
(
select a.`code`,((UNIX_TIMESTAMP(b.ctime) - UNIX_TIMESTAMP(a.ctime)) / 60)as mtime from
(
select (@on := @on + 1)as `on`,id,`code`,ctime from hp_report where content = 'on' order by ctime
)a
left join
(
select (@off := @off + 1)as `off`,id,`code`,ctime from hp_report where content = 'off' order by ctime
)b
on a.code = b.code and a.`on` = b.`off`
)m
group by m.`code`;
谢谢WWWWA你的sql语句对了。但是由于我的表中有百万条记录,所以比较慢,能不能优化下。非常感谢!!!
在CODE、content、ctime上建立索引