MYSQL:检测多标签用户

时间:2012-08-29 03:10:32

标签: mysql

说我有这张桌子:

+----+------+---------------------+-------------------------+
| id | user | timestamp           | referrer                |
+----+------+---------------------+-------------------------+
| 1  | foo  | 2012-08-26 14:05:55 | http://fubar.com/online |
+----+------+---------------------+-------------------------+
| 2  | foo  | 2012-08-26 14:05:59 | http://fubar.com/chat   |
+----+------+---------------------+-------------------------+
| 3  | bar  | 2012-08-27 07:06:07 | http://fubar.com/chat   |
+----+------+---------------------+-------------------------+
| 4  | max  | 2012-08-28 14:08:12 | http://fubar.com/chat   |
+----+------+---------------------+-------------------------+
| 5  | max  | 2012-08-28 14:08:36 | http://fubar.com/online |
+----+------+---------------------+-------------------------+

我想选择同时具有多个引荐来源的所有用户,并且时间戳与分钟精度相同

这意味着在1分钟的时间内,他们正在查看同一站点的2页,因此可能意味着它们是多表格的。所以在上表中,foo和max符合标准。

我想知道如何在mysql中实现这一点。

谢谢。

2 个答案:

答案 0 :(得分:1)

进行自我加入并在加入条件中使用TIMESTAMPDIFF()

SELECT DISTINCT a.user
FROM   my_table a JOIN my_table b ON
       a.user     =  b.user
   AND a.id       <  b.id
   AND a.referrer <> b.referrer
   AND ABS(TIMESTAMPDIFF(SECOND, a.timestamp, b.timestamp)) <= 60

sqlfiddle上查看。

答案 1 :(得分:0)

“有”条款怎么样?

SELECT user, COUNT(user) AS tabCount FROM whatever
 GROUP BY user
HAVING tabCount > 1;