我正在尝试使用用户定义的变量来限制子查询的结果,以便在某些分析数据中获得两个时间戳之间的差异。我正在使用的代码如下:
SELECT @visitID := `s`.`visit_id` AS `visit_id`, # Get the visit ID and assign to a variable
@dt := `s`.`dt` AS `visit`, # Get the timestamp of the visit and assign to a variable
`tmp`.`dt` AS `next-visit` # Get the 'next visit' timestamp which should be returned by the subquery
FROM `wp_slim_stats` AS `s` # From the main table...
LEFT JOIN (SELECT `s`.`visit_id`, # Start the subquery
MIN(`s`.`dt`) as `dt` # Get the lowest timestamp returned
FROM `wp_slim_stats` AS `s` # ...from the same table
WHERE `s`.`visit_id` = @visitID # Visit ID should be the same as the row the main query is working on
AND `s`.`dt` > @dt # Timestamp should be HIGHER than the row we are working on
LIMIT 0, 1) as `tmp` ON `tmp`.`visit_id` = `s`.`visit_id` # Join on visit_id
WHERE `s`.`resource` LIKE 'foo%' # Limit all results to the page we are looking for
目的是获取单独的综合浏览量并记录其访问ID和时间戳。然后,子查询应从具有相同访问ID的数据库返回 next 记录。然后,我可以从另一个中减去一个,以获得在页面上花费的秒数。
我遇到的问题是子查询似乎是为返回的每一行重新评估,而不是填充next-visit
列直到结束。这意味着返回的所有行都与最终行的子查询结果相匹配,因此除了最后一行之外,所有next-visit
列都是null
。
我正在寻找的结果将是:
_________________________________________________
| visit_id | visit | next-visit|
|--------------|---------------|----------------|
| 1 | 123456789 | 123457890 |
|--------------|---------------|----------------|
| 4 | 234567890 | 234567891 |
|--------------|---------------|----------------|
| 6 | 345678901 | 345678902 |
|--------------|---------------|----------------|
| 8 | 456789012 | 456789013 |
|______________|_______________|________________|
但我得到了
_________________________________________________
| visit_id | visit | next-visit|
|--------------|---------------|----------------|
| 1 | 123456789 | NULL |
|--------------|---------------|----------------|
| 4 | 234567890 | NULL |
|--------------|---------------|----------------|
| 6 | 345678901 | NULL |
|--------------|---------------|----------------|
| 8 | 456789012 | 456789013 |
|______________|_______________|________________|
我仍然很擅长在mySQL中使用变量,特别是在动态分配变量时。正如我所提到的,我认为我正在搞乱某个地方的操作顺序,这导致子查询在最后重新填充每一行。
理想情况下,由于来自客户端的限制,我需要能够在纯mySQL中执行此操作,因此不幸的是没有PHP。有可能做我想做的事吗?
谢谢!
答案 0 :(得分:1)
这里根本不需要变量。
SELECT `s`.`visit_id` AS `visit_id`,
`s`.`dt` AS `visit`,
(SELECT MIN(dt) FROM `wp_slim_stats` ws WHERE ws.visit_id = s.visit_id AND ws.dt > s.dt)
FROM `wp_slim_stats` AS `s`
WHERE `s`.`resource` LIKE 'foo%'
要回答为什么您的解决方案不起作用,请查看SQL查询中的操作顺序:
答案 1 :(得分:0)
这是您需要运行的查询。
选择visits.visitid为vId,temp.time为tTime,visits.time为vTime 来自访问内部联接(选择min(id)作为firstId,visitid,时间来自 访问v1 group by visitid)temp on visits.visitid = temp.visitid where id> temp.firstid group by visits.visitid;