2016-08-01 32 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