我有两个名称为raspi_E
和raspi_F
的表,其结构和列相同
id
,address
,device_time
。
raspi_E
表中有多个行具有相同的地址,但我想要最旧的行(相对于时间而言)。
例如,我的地址23
多次有device_time
个值2014-08-02 16:00:00
,2014-08-02 16:00:02
,2014-08-02 16:00:04
,我想要包含最早device_time
的行{1}},即2014-08-02 16:00:00
同样地,在raspi_F
表中,我有多个具有相同地址的行,我必须得到最旧的,在上面的示例中将是2014-08-02 16:10:00
。
现在,我需要在时间23
与raspi_E
的{{1}}地址2014-08-02 16:00:00
以及我raspi_F
的同一地址23
加入最早的设备标记{{1} }}
我尝试使用以下查询:
2014-08-02 16:10:00
使用上述查询时出现以下错误
1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法 靠近' WHERE(raspi_E.device_time BETWEEN' 2014-07-31 16:00:00' AND ' 2014-07-31 16:10:0'在第1行
我使用下面的查询来获取raspi_E中最旧的行值,并且它工作正常。
SELECT raspi_E.address, MIN(raspi_E.device_time)
AS time_D , MIN(raspi_F.device_time)
AS time_E
WHERE (raspi_E.device_time BETWEEN '2014-07-31 16:00:00' AND
'2014-07-31 16:10:00' GROUP BY raspi_E.address) AND
(raspi_F.device_time BETWEEN '2014-07-31 16:03:00' AND
'2014-07-31 16:25:00' GROUP BY raspi_F.address)
AND raspi_E.address=raspi_F.address
答案 0 :(得分:2)
您错过了FROM
条款和JOIN
:
SELECT raspi_E.address,
MIN(raspi_E.device_time) AS time_D ,
MIN(raspi_F.device_time) AS time_E
WHERE (raspi_E.device_time BETWEEN '2014-07-31 16:00:00' AND '2014-07-31 16:10:00' GROUP BY raspi_E.address) AND (raspi_F.device_time BETWEEN '2014-07-31 16:03:00' AND '2014-07-31 16:25:00' GROUP BY raspi_F.address) AND raspi_E.address=raspi_F.address
应该是:
SELECT raspi_E.address,
MIN(raspi_E.device_time) AS time_D ,
MIN(raspi_F.device_time) AS time_E
FROM raspi_E
INNER JOIN raspi_F USING <Whatever_key>
WHERE (raspi_E.device_time BETWEEN '2014-07-31 16:00:00' AND '2014-07-31 16:10:00' GROUP BY raspi_E.address) AND (raspi_F.device_time BETWEEN '2014-07-31 16:03:00' AND '2014-07-31 16:25:00' GROUP BY raspi_F.address) AND raspi_E.address=raspi_F.address
答案 1 :(得分:1)
因为你在哪里/分组时遇到问题...这应该可以帮到你......
SELECT
OldestE.Address,
OldestE.ETime,
OldestF.FTime
from
( SELECT
E.address,
MIN(E.device_time) ETime
from
raspi_E E
where
E.Device_Time between '2014-07-31 16:00:00' AND '2014-07-31 16:10:00'
group by
E.address ) OldestE
JOIN ( SELECT
F.address,
MIN(F.device_time) FTime
from
raspi_F F
where
F.device_time BETWEEN '2014-07-31 16:03:00' AND '2014-07-31 16:25:00'
group by
F.address ) OldestF
ON OldestE.Address = OldestF.Address