在mysql的日志表中首次出现事件

时间:2015-06-26 00:37:21

标签: mysql sql join group-by

我有一个日志表: user_id,path_id,poi_id,timestamp,event_type

它就像博物馆中的灯塔数据库,但它是音频巡演系统的一部分,人们可以在同一场地内选择不同的路径。

示例:

John, Strolling at the Zoo Tour,Beacon_1, 2015-05-05 11:49, "WentAcross"
Zoe, An adventure in the Lion's Lair, Beacon_15, 2015-05-05 11:50, "WentAcross"
John, Strolling at the Zoo Tour, Beacon_3, 2015-05-05 11:50, "WentAcross"
John, Strolling at the Zoo Tour, Beacon_4, 2015-05-05 11:51, "WentAcross"
Kyle, Strolling at the Zoo Tour,Beacon_4, 2015-05-05 11:51, "WentAcross"
Zoe, An adventure in the Lion's Lair, Beacon_15, 2015-05-05 11:50, "WentAcross"
Zoe, An adventure in the Lion's Lair, Beacon_1, 2015-05-05 11:51, "WentAcross"
John, Strolling at the Zoo Tour, Beacon_6, 2015-05-05 11:51, "WentAcross"
John, Strolling at the Zoo Tour, Beacon_5, 2015-05-05 11:52, "WentAcross"
John, Strolling at the Zoo Tour, Beacon_2, 2015-05-05 11:53, "WentAcross"

我想知道路径内的时间戳首次触及特定用户的poi次数。

在此示例中,结果应为:

  • Beacon_1 1(作为John的第一点被触及,对于Zoe来说,它并非如此 首先......可以是路径交叉,或者只是在其他地方加入)
  • Beacon_15 2(作为Zoe和Kyle在Lion的第一点被触及 巢穴之旅)
  • Beacon_4 1(作为漫步的第一点被触及 Zoe的动物园之旅 - 她似乎在中途连接了)

每个其他Beacon_ID应读为零。

我怎样才能构建这样的查询?

2 个答案:

答案 0 :(得分:1)

将您的表格列为' name',' beacon',' timestamp'和表名'事件' ...我想到了一张临时表...这样的事情:

SELECT GROUP_CONCAT(evt.name), tmp_evt.beacon, tmp_min_ts, COUNT(1) as touching
FROM events evt 
INNER JOIN (
   SELECT evt.beacon AS beacon, MIN(timestamp) AS min_ts
   FROM events evt
   GROUP BY evt.beacon
 ) tmp_evt ON (tmp_evt.min_ts = evt.timestamp AND tmp_evt.beacon = evt.beacon)
GROUP BY tmp_evt.beacon

答案 1 :(得分:0)

如果不了解您实际要求的内容会更有效吗?

SELECT COUNT(*), timestamp
FROM log_table
WHERE user_id = 123
AND poi_id = 321
AND path_id BETWEEN 123 AND 321
GROUP BY timestamp;