2017-03-01 62 views
0

我正在構建用戶工作負載的報告圖表顯示活動任務,暫停和未啓動,但在我的'已暫停'結果中我還檢索活動作業MYSQL排除行,如果最大ID有一列是NULL

SELECT 'active' AS `status`,COUNT(DISTINCT TA.`task_id`) AS `tasks`,U.uID AS `user_id`, 
    CONCAT(U.`firstname`, ' ', U.`lastname`) AS `user` 
    FROM `tasks` TA 
    INNER JOIN `users` U on U.`uID`=TA.`scheduled_to_user` 
    INNER JOIN `ticket` T on T.`tID`=TA.`ticketFK` 
    INNER JOIN `task_activity_log` TL ON TL.`task_id`=TA.`task_id` 
    INNER JOIN `project` P ON P.`pID`=T.`pFK` 
    WHERE TA.`started_on` IS NOT NULL 
    AND TA.`completed_on` IS NULL 
    AND TL.`start_ts` IS NOT NULL 
    AND TL.`end_ts` IS NULL 
    AND T.`closed_on` IS NULL 
    GROUP BY U.`uID` 
    UNION 
    SELECT 'paused' AS `status`, COUNT(DISTINCT TA.`task_id`) AS `tasks`,U.uID AS `user_id`, 
    CONCAT(U.`firstname`, ' ', U.`lastname`) AS `user` 
    FROM `tasks` TA 
    INNER JOIN `system_users` U on U.`uID`=TA.`scheduled_to_user` 
    INNER JOIN `task_activity_log` TL ON TL.`task_id`=TA.`task_id` 
    INNER JOIN `icket` T on T.`tID`=TA.`ticketFK` 
    INNER JOIN `project` P ON P.`pID`=T.`pFK` 
    WHERE TA.`started_on` IS NOT NULL 
    AND TA.`completed_on` IS NULL 
    AND T.`closed_on` IS NULL 
    AND TL.`start_ts` IS NOT NULL 
    AND TL.`end_ts` IS NOT NULL 
    GROUP BY U.`uID` 
    UNION 
    SELECT 'not started' AS `status`, COUNT(DISTINCT TA.`task_id`) AS `tasks`,U.uID AS `user_id`, 
    CONCAT(U.`firstname`, ' ', U.`lastname`) AS `user` 
    FROM `tasks` TA 
    INNER JOIN `users` U on U.`uID`=TA.`scheduled_to_user` 
    INNER JOIN `ticket` T on T.`tID`=TA.`ticketFK` 
    INNER JOIN `project` P ON P.`pID`=T.`pFK` 
    WHERE TA.`started_on` IS NULL 
    AND TA.`completed_on` IS NULL 
    AND T.`closed_on` IS NULL 
    GROUP BY U.`uID` 

的task_activity_log表看起來是這樣的:

| id | task_id | start_ts     | end_ts    | 
    1  1  2017-02-28 15:47:34   2017-02-28 15:47:34 
    2  1  2017-02-28 15:47:34   (NULL) 
    3  2  2017-02-28 15:47:34   2017-02-28 15:47:34 
    4  2  2017-02-28 15:47:34   2017-02-28 15:47:34 

ID 2是活動任務。香港專業教育學院試圖通過嘗試新事物得到每個任務的最大ID(最新活動),如

LEFT JOIN (SELECT MAX(`id`)AS `max_id`,`task_id` AS `task_id` FROM`task_activity_log`) MA ON MA.`task_id`=TA.`task_id` 

(SELECT MAX(`id`) FROM`task_activity_log` A1 WHERE A1.`task_id`=TA.`task_id`) AS `max_id` 

但我不能讓這個我的邏輯正確的(認爲我一直在尋找它太長) 任何幫助,將不勝感激

回答

1

你正在試圖做的是與自身的聚合過濾task_activity_log什麼(上次登錄任務活動)。

你需要的是像

select ts.* 
from 'task_activity_log' as 'ts' 
join (select 'task_id', max('id') as 'id' from 'task_activity_log' group by 'task_id') as 'max_ts' 
on ts.'task_id' = max_ts.'task_id' and ts.'id' = max_ts.'id' 

這樣,你只考慮到task_activity_log參照最新活動行。

相關問題