我有另一种方法
SET @given_user = 7;
SET @dt = '2013-05-03';
SET @dt1 = @dt + INTERVAL 0 SECOND;
SET @dt2 = @dt + INTERVAL 1 DAY;
SELECT
SEC_TO_TIME(SUM(dts)) TotalTime
FROM
(
SELECT
(IF(object_id=2,-1,1) *
(UNIX_TIMESTAMP(date_event) -
UNIX_TIMESTAMP(DATE(date_event) +INTERVAL 0 SECOND))) dts
FROM
event_log
WHERE
user_id=@given_user AND
object_id IN (2,3) AND
date_event >= @dt1 AND
date_event < @dt2
) A;
这是您的示例数据
use test
DROP TABLE IF EXISTS event_log;
CREATE TABLE event_log
(
id INT NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL,
object_id INT NOT NULL,
date_event DATETIME,
PRIMARY KEY (id)
);
INSERT into event_log
(user_id,object_id,date_event) VALUES
(7,2,'2013-05-03 08:37:11'),
(7,3,'2013-05-03 12:43:51'),
(7,2,'2013-05-03 15:33:41'),
(7,3,'2013-05-03 17:10:01');
在这里加载
use test
Database changed
mysql> DROP TABLE IF EXISTS event_log;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE event_log
-> (
-> id INT NOT NULL AUTO_INCREMENT,
-> user_id INT NOT NULL,
-> object_id INT NOT NULL,
-> date_event DATETIME,
-> PRIMARY KEY (id)
-> );
Query OK, 0 rows affected (0.05 sec)
mysql> INSERT into event_log
-> (user_id,object_id,date_event) VALUES
-> (7,2,'2013-05-03 08:37:11'),
-> (7,3,'2013-05-03 12:43:51'),
-> (7,2,'2013-05-03 15:33:41'),
-> (7,3,'2013-05-03 17:10:01');
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql>
这是执行的查询
mysql> SET @given_user = 7;
Query OK, 0 rows affected (0.00 sec)
mysql> SET @dt = '2013-05-03';
Query OK, 0 rows affected (0.00 sec)
mysql> SET @dt1 = @dt + INTERVAL 0 SECOND;
Query OK, 0 rows affected (0.00 sec)
mysql> SET @dt2 = @dt + INTERVAL 1 DAY;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT
-> SEC_TO_TIME(SUM(dts)) TotalTime
-> FROM
-> (
-> SELECT
-> (IF(object_id=2,-1,1) *
-> (UNIX_TIMESTAMP(date_event) -
-> UNIX_TIMESTAMP(DATE(date_event) +INTERVAL 0 SECOND))) dts
-> FROM
-> event_log
-> WHERE
-> user_id=7 AND
-> object_id IN (2,3) AND
-> date_event >= @dt1 AND
-> date_event < @dt2
-> ) A;
+-----------+
| TotalTime |
+-----------+
| 05:43:00 |
+-----------+
1 row in set (0.00 sec)
mysql>
试试看 !!!