1

我的mysql表是这样的:

+---------+---------+------------+-----------------------+---------------------+
| visitId | userId  | locationId | comments              | time                |
+---------+---------+------------+-----------------------+---------------------+
|       1 |    3    |     12     | It's a good day here! | 2012-12-12 11:50:12 |
+---------+---------+------------+-----------------------+---------------------+
|       2 |    3    |     23     | very beautiful        | 2012-12-12 12:50:12 |
+---------+---------+------------+-----------------------+---------------------+
|       3 |    3    |     52     | nice                  | 2012-12-12 13:50:12 |
+---------+---------+------------+-----------------------+---------------------+

女巫记录来访者的轨迹和对去过的地方的一些评论

我想查找一天内访问过多个地方的访客,以及具体的日期和地点,而不仅仅是计数。

我尝试了子查询:

mysql> SELECT userId, locationId, time FROM visits 
WHERE (userId,DATE(time)) in (
  SELECT  userNum, Date(weiboTime) from visits GROUP BY userNum, Date(wei
  boTime) Having COUNT(*)>1);

和联合查询:

mysql> select v2.userId, v1.loacationId, v1.time from visits as v1, visits as
v2 where v1.userId=v2.userId GROUP BY v2.userId, Date(v2.time) HAVING 
COUNT(DISTINCT v2.locationId);

我不确定第二个是否正确。但是两者都需要很长时间。关于我应该怎么做的任何建议?

更新

mysql> SELECT t.userId, locationId, t.time FROM (
              SELECT userId, time 
              FROM visits GROUP BY userId,Date(time)
              HAVING COUNT(*) > 1) AS t, visits 
       WHERE t.userId=visits.userId AND t.time=visits.time;

希望这会让我自己更清楚。

4

2 回答 2

3

您的查询包括 locationId,但您的既定目标是获取一天内访问次数超过 1 次的用户/日期组合。这是得到它的sql:

select userId, date(time), count(*)
from visits
group by userId, date(time)
having count(*) > 1;

更新: 要获得大于 1 的用户/天组合访问的所有访问:

select *
from visits
where (userId, date(time)) in (
    select userId, date(time)
    from visits
    group by userId, date(time)
    having count(*) > 1);
于 2013-03-21T03:59:55.617 回答
0

我认为你会更适合GROUP BY子查询中使用你的计数。从MySQL 的计数文档中,您可以执行以下操作:

mysql> SELECT userId, locationId, time, visitCount
       FROM
           (SELECT COUNT(*) as visitCount 
            FROM visits 
            GROUP BY userId)
       WHERE visitCount > 1;

我假设您遇到的缓慢来自您的子句中的HAVINGand 。DISTINCTWHERE

于 2013-03-21T04:12:20.863 回答