我有一张名为"维护"和另一个"进程"和"汽车"。 的维护:
id car_id process_id date
1 1 1 4/26/2013
2 1 1 5/26/2013
3 1 2 5/26/2013
我想根据最大日期为car_id和process_id重复选择不同的值。所以我想:
id car_id process_id date
2 1 1 5/26/2013
3 1 1 5/26/2013
我有这个:
SELECT m.*, u.username, c.milage, p.*, s.name
FROM maintenances as m
LEFT JOIN users AS u
ON u.id = m.user_id
LEFT JOIN cars AS c
ON c.id = m.car_id
LEFT JOIN processes as p
ON p.id = m.process_id
LEFT JOIN services as s
ON s.id = m.service_id
Group by m.car_id, m.process_id
但是这给了我:
id car_id process_id date
1 1 1 4/26/2013
3 1 2 5/26/2013
我想:
id car_id process_id date
2 1 1 5/26/2013
3 1 2 5/26/2013
答案 0 :(得分:3)
尝试将maintenances
加入带有MAX(date)
的子查询:
SELECT m.*, u.username, c.milage, p.*, s.name
FROM maintenances as m
JOIN
(SELECT car_id, process_id, MAX(date) as MAX_DATE
FROM maintenances
GROUP BY by car_id, process_id) as MAX_T ON m.car_id = MAX_T.car_id
AND m.process_id = MAX_T.process_id
AND m.date = MAX_T.MAX_DATE
LEFT JOIN users AS u ON u.id = m.user_id
LEFT JOIN cars AS c ON c.id = m.car_id
LEFT JOIN processes AS p ON p.id = m.process_id
LEFT JOIN services AS s ON s.id = m.service_id