如果max id具有NULL的列,则MYSQL排除行

时间:2017-03-01 09:11:23

标签: php mysql join left-join

我正在构建一个用户工作负载的报告图表,显示活动任务,暂停但未启动但在我的结果中暂停'我也正在检索一份有效的工作

HTTP/1.0 200 OK
Content-Type: application/json 
Location: http://localhost:5000/todo/1
Content-Length: 46
Server: Werkzeug/0.10.4 Python/2.7.13
Date: Wed, 01 Mar 2017 09:09:11 GMT


* Closing connection 0 
{"UserID": 2, "details": "test", "todo_ID": 1}

task_activity_log表看起来像这样:

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`

id 2是一项活动任务。香港专业教育学院尝试通过尝试

等方式获得每项任务的最大ID(最新活动)
| 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

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`

但我无法理解我的逻辑(想想我已经看了太长时间) 任何帮助将不胜感激

1 个答案:

答案 0 :(得分: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行。