MYSQL查询帮助JOIN表

时间:2015-02-12 19:10:34

标签: mysql sql

我在查询时遇到了一些问题,希望有人可以指导我完成这项工作?我认为这应该可以实现。我有两张桌子。表A存储小时数,表B存储驾驶时间。我想让所有在一天工作超过6个小时的人能够做到。但是我还需要在特定的一天获得驾驶时间,他们一天的工作时间超过6小时。我希望我有道理。这是我现在正在使用的查询,并且正在努力让每天工作超过6小时的每个人都能得到会议记录。驾驶时间存储在表B中,称为ies_mileage,字段为持续时间。我尝试了几件事但没有成功。

SELECT 
    wk_date,
    full_name, 
    SUM(hours) AS HOURS 
FROM `ies_weekly` 
    LEFT JOIN infant_specialist 
        ON ies_weekly.is_id = infant_specialist.is_id 
WHERE wk_date BETWEEN '2015-01-16' AND '2015-01-31' 
GROUP BY 
    DAY(wk_date), 
    ies_weekly.is_id 
HAVING SUM(hours) > 6 
ORDER BY full_name  ASC

这是有效的,当我试图添加持续时间时,总数变得混乱并且它不再准确。这是我试过的

SELECT 
    wk_date,
    full_name, 
    SUM(hours) AS HOURS, 
    SUM(duration) AS minutes 
FROM 
    `ies_weekly` 
    LEFT JOIN infant_specialist 
        ON ies_weekly.is_id = infant_specialist.is_id 
    LEFT JOIN ies_mileage 
        ON ies_weekly.wk_date = ies_mileage.mil_date 
        AND ies_weekly.is_id = ies_mileage.ies_id 
WHERE wk_date BETWEEN '2015-01-16' AND '2015-01-31' 
GROUP BY 
    DAY(wk_date), 
    ies_weekly.is_id 
HAVING SUM(hours) > 6
ORDER BY full_name  ASC

1 个答案:

答案 0 :(得分:0)

SELECT full_name, wk_date, SUM(hours) HOURS,
    (Select Sum(duration)
     From ies_mileage
     Where mil_date = w.wk_date
         and ies_id = w.is_id) DrivingTime
FROM ies_weekly w
    LEFT JOIN infant_specialist i
     ON i.is_id = w.is_id 
WHERE wk_date BETWEEN '2015-01-16' AND '2015-01-31' 
GROUP BY DAY(wk_date), w.is_id 
HAVING SUM(hours) > 6 
ORDER BY full_name ASC