我有以下查询;
SELECT count(*) as aggregate
FROM cars
INNER JOIN snapshots ON cars.snapshot_id=snapshots.id
WHERE cars.snapshot_id=194340
正常工作 - 使用特定的snapshot_id计算所有汽车。
但是现在我只想计算从创建快照到那里过去1小时以上的汽车。
我试过这个 - 但它不起作用:
SELECT count(*) as aggregate
FROM cars
INNER JOIN snapshots ON cars.snapshot_id=snapshots.id
WHERE cars.snapshot_id=194340
AND time_arrive_destination <= DATE_SUB('snapshots.created_at', INTERVAL 1 HOUR)
我知道我已经关闭了 - 因为如果我对来自snapshots.created_at
的时间戳进行硬编码 - 就可以了:
SELECT count(*) as aggregate
FROM cars
INNER JOIN snapshots ON cars.snapshot_id=snapshots.id
WHERE cars.snapshot_id=194340
AND time_arrive_destination <= DATE_SUB("2015-08-31 20:29:49", INTERVAL 1 HOUR)
那么如何将加入的列字段snapshots.created_at
用作date_sub()
的变量?
答案 0 :(得分:1)
如果您需要(或想要)转义标识符(例如列名,因为它是保留字),请将标识符用反引号字符括起来,而不是单引号,例如
AND time_arrive_destination <= DATE_SUB(`snapshots`.`created_at`, INTERVAL 1 HOUR)