我有以下数据集:
id changeType dateTimeStamp userName
1 insert 07/02/2015 0:15:53 john
2 update 07/02/2015 0:15:52 adriana
3 insert 07/02/2015 0:15:51 john
4 update 07/02/2015 0:15:50 john
5 update 07/01/2015 22:46:57 denise
我正在尝试检索相互覆盖彼此在5分钟内进行更改的数据的用户。对于这些特定的数据集,我应该得到ID 1,2和3。
我试过了:
SELECT *
FROM tblChanges v1
INNER JOIN tblChanges v2
ON v2.userName <> v1.userName
AND v1.dateTimeStamp <> v2.dateTimeStamp
WHERE ABS( TIMESTAMPDIFF(MINUTE, v1.dateTimeStamp, v2.dateTimeStamp ) ) <= 5
这也检索了我不需要的ID = 4。有什么帮助吗?
提前感谢。
编辑:输出
id changeType dateTimeStamp userName
1 insert 07/02/2015 0:15:53 john
2 update 07/02/2015 0:15:52 adriana
3 insert 07/02/2015 0:15:51 john
编辑:这是DDL / DML
CREATE TABLE `tblChanges` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`changeType` VARCHAR(50) DEFAULT NULL,
`dateTimeStamp` DATETIME NOT NULL ON UPDATE CURRENT_TIMESTAMP,
`userName` VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1 ;
INSERT INTO tblChanges ( id, changeType, dateTimeStamp, userName )
VALUES (1, 'insert' , '2015-07-02 12:15:53', 'john' ) ;
INSERT INTO tblChanges ( id, changeType, dateTimeStamp, userName )
VALUES (2, 'update' , '2015-07-02 12:15:52', 'adriana' ) ;
INSERT INTO tblChanges ( id, changeType, dateTimeStamp, userName )
VALUES (3, 'insert' , '2015-07-02 12:15:51', 'john' ) ;
INSERT INTO tblChanges ( id, changeType, dateTimeStamp, userName )
VALUES (4, 'update' , '2015-07-02 12:15:50', 'john' ) ;
INSERT INTO tblChanges ( id, changeType, dateTimeStamp, userName )
VALUES (5, 'update' , '2015-07-01 22:46:57', 'denise' ) ;
答案 0 :(得分:0)
您的联接正在选择当前记录之前和之后发生的记录,而不是仅在之后记录。
推荐:
SELECT *
FROM tblChanges v1
INNER JOIN tblChanges v2
ON v2.userName <> v1.userName
AND v2.dateTimeStamp BETWEEN v1.dateTimeStamp AND DATE_ADD(v1.dateTimeStamp, INTERVAL 5 MINUTE)