【发布时间】:2016-07-21 11:17:18
【问题描述】:
我有一个 MySQL 表
- row_id(主要)
- user_id
- user_ip
- date_start(unix 时间戳)
- date_end(unix 时间戳)
我只想选择这张表的用户 ID(不同)IF 至少有 2 个连续行 WHERE
[row X] 中的 user_ip 与 [row X+1] 中的 user_ip 不同
与
ABS([row X] 中的 date_end - [row X+1] 中的 date_start)
Rows应该按row_id ASC排序,这样我们就可以连续得到第X、X+1等行。
我用 PHP 很容易做到这一点,但它非常慢,所以我认为只使用 sql 就可以完成。
示例
row_id | user_id | user_ip | date_start | date_end
1 , 1 , 127.0.0.1 , 1469100096 , 1469100099
2 , 2 , 5.5.5.5 , 1469100054 , 1469100055
3 , 3 , 4.4.4.4 , 1469100032 , 1469100036
4 , 1 , 6.6.6.6 , 1469100117 , 1469100099
5 , 4 , 127.0.0.1 , 1469100001 , 1469100005
6 , 2 , 127.0.0.1 , 1469100555 , 1469100565
由此,我们应该只得到用户 ID 1,因为用户 id 1 在连续 2 行中具有不同的 IP + 第一行的 date_end (1469100099) - 下一行的开始日期 1(469100117) = 18这是
我们不应该返回用户 ID 2,因为虽然它验证了第一个条件,但它没有验证带有 date_end 和 date_start 的第二个条件。
【问题讨论】:
-
看看:stackoverflow.com/questions/9824948/... 并尝试这样的事情:SELECT parent.id FROM tableName AS parent inner join tableName AS child ON parent.user_ip != child.user_ip and DATE_SUB ((parent.date_end -child.date_start), INTERVAL 20 HOUR) and parent.user_id = child.user_id;