我正在尝试使用用户定义的变量来限制子查询的结果,以获取某些分析数据中两个时间戳之间的差异。我正在使用的代码如下:
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-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。有可能做我想做的事吗?
谢谢!