2016-08-01 67 views
1

我有两个表,我想获得按标记分组的任务的日志记录总和,大多数时间子任务具有与父母,但在某些情况下,他们不。如果从子任务标记为空,从父任务继承标记

如何获取按标记分组的记录分钟总数,包括子任务,因此如果他们没有标记,他们会继承父标记。

任务

+-----+-----------+------+-------+------------+ 
| id | parent-id | name | tag | is-subtask | 
+-----+-----------+------+-------+------------+ 
| 001 |   | a | sales |   0 | 
| 002 |  001 | b | sales |   1 | 
| 003 |  001 | c |  |   1 | 
| 004 |   | d | store |   0 | 
+-----+-----------+------+-------+------------+ 

+-----+---------+-------------+----------------+ 
| id | task-id | description | logged-minutes | 
+-----+---------+-------------+----------------+ 
| 991 |  001 | Time for a |    15 | 
| 992 |  002 | Time for ab |    60 | 
| 993 |  002 | Time for ab |    75 | 
| 994 |  003 | Time for ac |    35 | 
| 995 |  004 | Time for d |    20 | 
+-----+---------+-------------+----------------+ 

回答

0

基本上你需要使用COALESCE()函数返回在列表中找到第一个非空值(如果只有空值,它评估为空)。

当您从派生表(查询的内部部分)获得有关标签的信息后,可以将该信息加入times表以计算每个标签的总和。

我还没有测试代码,但我相信它应该可以工作 - 这假定你的关系只有1层深。如果您有更深的层次结构,请查看How to create a MySQL hierarchical recursive query以了解对此代码的一些调整。

SELECT 
    alltasks.tag 
    , SUM(times.logged-minutes) AS logged-minutes 
FROM (
    -- take parent tasks 
    SELECT 
     tparent.id 
     , tparent.tag 
    FROM task tparent 
    UNION 
    -- take child tasks 
    SELECT 
     tchild.id 
     , COALESCE(tchild.tag, tparent.tag) -- if no child tag, use parent tag 
    FROM task tparent 
    INNER JOIN task tchild ON 
     tparent.id = tchild.parent-id 
     AND tchild.is-subtask = 1 -- may not be necessary unless you have different relationships 
    ) alltasks 
LEFT JOIN times ON 
    alltasks.id = times.task-id 
GROUP BY alltasks.tag