通过外键查找Max()值

时间:2011-11-30 19:04:17

标签: mysql sql database aggregate-functions

考虑这个数据库结构:

 __________                 __________
| Trucks   |               | Mileage  |
|__________|__________     |__________|________________________
| ID    | DRIVER      |    | TRUCK_ID  | MILEAGE  | OIL_CHANGE |
|---------------------|    |-----------------------------------|
| 1     | Tony        |    | 1         | 100000     105000     |
| 2     | George      |    | 2         | 6020       10020      |
| 3     | Mary        |    | 3         | 37798      41000      |
|_____________________|    | 3         | 41233      47200      |
                           | 3         | 49000                 |
                           |___________________________________|

我希望最终得到一个结果集,其中包含每个驾驶员的最大里程和最大油量变化。

_________________________________
| 1  | Tony  |  100000 | 105000 |
| 2  | George|  6020   | 10020  |
| 3  | Mary  |  49000  | 47200  |
|_______________________________|

这是我到目前为止所尝试的:

SELECT t.*, MAX(m.mileage) AS mileage, MAX(m.oil_change) AS oil_change
FROM trucks t
LEFT JOIN mileage m ON t.id = m.truck_id
GROUP BY t.id

但这似乎不允许MAX功能正常工作。它并不总是包含mileage

的实际最大值

2 个答案:

答案 0 :(得分:6)

知道了!您的里程列必须定义为字符类型,而不是数字类型!当发生时,订单按字母顺序完成,而不是按值完成。

您应该将mileageoil_change列转换为数字类型(我建议根据提供的数据样本INT)。

虽然你没有转换它们,但这将有效:

SELECT t.*, MAX(cast(m.mileage as int)) AS mileage, 
            MAX(cast(m.oil_change as int)) AS oil_change
FROM trucks t
LEFT JOIN mileage m ON t.id = m.truck_id
GROUP BY t.id

答案 1 :(得分:0)

以下查询应该适用于您的问题。

SELECT T.DRIVER,MIN(MILEAGE) AS MIN_MILEAGE,MIN(OIL_CHANGE) AS MIN_OIL_CHANGE
FROM TRUCKS T INNER JOIN MILEAGE M
ON T.ID = M.TRUCK_ID
GROUP BY T.DRIVER;


SELECT T.DRIVER,MAX(MILEAGE) AS MAX_MILEAGE,MAX(OIL_CHANGE) AS MAX_OIL_CHANGE
FROM TRUCKS T INNER JOIN MILEAGE M
ON T.ID = M.TRUCK_ID
GROUP BY T.DRIVER;

此致 Venk