以先前的问题为基础,此处(堆栈溢出):How to efficiently pre-filter rows in conjunction with a join?
Nick为该问题提供了更为通用的解决方案,如下所示。
特别值得注意的是,每个“ diff / 2”第二次使用“ diff”,而我现在已经成功多次使用了该概念。
问题是我还有另一个无法正常运行的示例,我无法理解原因。似乎是MariaDB / mysql的“解析”问题,但我是新手。 ;-)
感谢您的见解。 = D
功能/工作示例:
SELECT scanid,
event_id,
object_id,
obj_timestamp,
obj_counter,
diff,
diff / 2 AS hdiff
FROM (SELECT t1.scanid,
t1.event_id,
t1.object_id,
t1.obj_timestamp,
t1.obj_counter,
Timediff(t1.obj_timestamp, t2.obj_timestamp) AS diff
FROM event_data AS t1
LEFT JOIN event_data AS t2
ON t2.obj_counter = t1.obj_counter - 1
AND t2.object_id = t1.object_id
WHERE t1.object_id = 2
ORDER BY t1.obj_counter) AS diffs
我的代码-除非我尝试替换注释掉的显示行,否则此代码有效:
SET @distance=1000;
SELECT event_id,
timestamp,
t1.overall_time,
TIME_TO_SEC(t1.overall_time) AS overall_secs,
-- @distance / overall_secs AS overall_kph
@distance / TIME_TO_SEC(t1.overall_time) AS overall_kph
FROM (SELECT event_id,
timestamp,
TIMEDIFF(MAX(timestamp), MIN(timestamp)) AS overall_time
FROM summary
GROUP BY event_id) AS t1;
当我尝试将其指定为列后立即尝试参照total_secs时给出的错误(用注释的内容替换@distance行以查看此错误):
ERROR 1054 (42S22) at line 120 in file: 'summary.sql': Unknown column 'overall_secs' in 'field list'
答案 0 :(得分:1)
抱歉,SQL无法那样工作。直到多个步骤之后,“别名”才可用。我认为该标准允许SELECT
中的“列”以任意顺序进行评估。
因此,您注释掉的行也可能是
@distance / TIME_TO_SEC(t1.overall_time) AS overall_kph