比MAX更早的Mysql数据条目(日期)

时间:2011-08-03 08:39:02

标签: mysql

我有两个表,一个有设备,有相应的服务时间。每个设备都可以有多种服务。我正在寻找服务时间超过3个月的设备。我试过这个,这当然没有用:

SELECT devices.id, 
       devices.name,  
       services.servicetime 
FROM devices
    LEFT JOIN services 
        ON services.device_id = devices.id
WHERE MAX(services.servicetime) < DATE_SUB(NOW(), INTERVAL 3 MONTH);

如何获得理想的结果?

4 个答案:

答案 0 :(得分:2)

GROUP BY devices.id添加到您的查询中,并将条件更改为HAVING子句(在分组后评估)。您需要每个设备MAX(services.servicetime) ,其中您的当前结果集每个服务包含一行。

SELECT
  devices.id,
  devices.name,
  MAX(services.servicetime)
FROM
  devices
LEFT OUTER JOIN
  services
ON
  services.device_id = devices.id
GROUP BY
  devices.id
HAVING
  MAX(services.servicetime) < CURRENT_TIMESTAMP - INTERVAL 3 MONTH

如果您想要包含从未提供过服务的设备,请将OR MAX(services.servicetime) IS NULL添加到最后。

答案 1 :(得分:1)

SELECT devices.id, devices.name, MAX(services.servicetime)
FROM 
    devices
    LEFT JOIN
    services ON services.device_id=devices.id
GROUP BY
    devices.id, devices.name
HAVING
    MAX(services.servicetime) < DATE_SUB(NOW(), INTERVAL 3 MONTH)
    OR
    MAX(services.servicetime) IS NULL;

答案 2 :(得分:0)

select devices.id,devices.name.services.servicetime from devices,services
where services.id = devices.id and services.id in 
(select services.id from services where
 DATE_SUB(NOW(), INTERVAL 3 MONTH) GROUP by services.id)

答案 3 :(得分:0)

GROUP BY and HAVING是您的条款:

SELECT devices.id, devices.name, max(services.servicetime) FROM devices
LEFT JOIN services ON services.device_id=devices.id
GROUP BY devices.id, devices.name
HAVING MAX(services.servicetime) < DATE_SUB(NOW(), INTERVAL 3 MONTH);