sql选择distinct最大日期

时间:2014-05-25 15:29:41

标签: mysql sql

我有3张桌子"维护","汽车","用户" 。我想从表维护中选择所有数据,使用不同的car_id和每个不同的最后一条记录(基于max maintenance_date)

SELECT
     m. * , u.username, c.Model, c.Make, c.License, c.Milage, COUNT( m.process_id ) AS count_nr
    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

    WHERE
    maintenance_date = (SELECT MAX(maintenance_date) FROM maintenances WHERE car_id = m.car_id)

问题是此查询只返回一条记录,该记录具有所有记录的最大日期。我想要所有记录(不同的car_id和具有相同car_id的记录仅显示max(maintenance_date)的值)

2 个答案:

答案 0 :(得分:0)

添加GROUP BY u.username

 WHERE
maintenance_date = (SELECT MAX(maintenance_date) FROM maintenances WHERE car_id = m.car_id)
 GROUP BY u.username

答案 1 :(得分:0)

这是您的查询:

SELECT m. * , u.username, c.Model, c.Make, c.License, c.Milage, COUNT( m.process_id ) AS count_nr
----------------------------------------------------------------^
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
WHERE maintenance_date = (SELECT MAX(maintenance_date) FROM maintenances WHERE car_id = m.car_id);

这是一个聚合查询。如果没有group by,则只返回一行(所有行都在一个组中)。所以,添加group by

SELECT m. * , u.username, c.Model, c.Make, c.License, c.Milage, COUNT( m.process_id ) AS count_nr
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
WHERE maintenance_date = (SELECT MAX(m2.maintenance_date) FROM maintenances m2 WHERE m2.car_id = m.car_id);
GROUP BY c.id

我还修复了关联语句,清楚它与外部查询相关。