Mysql查询(where和group)

时间:2012-07-11 10:40:10

标签: mysql sql

我有两张桌子

tbl_activities

 id | activity 
 1  | activity1
 2  | activity2

tbl_sub_activities

id |activityId   | subActivity   | status 
 1 |  1          | subActivity1  | done
 2 |  1          | subActivity2  | done
 3 |  1          | subActivity3  | ongoing
 4 |  2          | subActivity4  | done
 5 |  2          | subActivity5  | done

方案:
活动可以有许多子活动。

如果完成了子活动的状态,则完成活动,
如果子活动状态仍在持续,则活动正在进行中。

问题:
如何查询tbl_activities以获得这样的输出。

 id | activity  | status
 1  | activity1 | ongoing
 2  | activity2 | done

我使用PHP完成了这项工作,但我想知道如何使用SQL查询来完成此操作。

3 个答案:

答案 0 :(得分:3)

根据您的模型,您可以使用这个真正高效的查询:

SELECT
    a.id,
    a.activity,
    MAX(s.status) as status
FROM tbl_activities a
INNER JOIN tbl_sub_activities s ON s.activityId = a.id
GROUP BY a.id;

但请注意,依赖于模型MAX(statuts)将始终提供ongoing,除非所有子活动都是done; - )

对于较少依赖于模型的查询,您可以考虑以下模式:

SELECT
    a.id,
    a.activity,
    SUM(s.status = "ongoing") as NB_ONGOING,
    SUM(s.status = "done") as NB_DONE
FROM tbl_activities a
INNER JOIN tbl_sub_activities s ON s.activityId = a.id
GROUP BY a.id;

答案 1 :(得分:1)

如果您只有两个状态已完成且正在进行,则此查询可能适用于您

   Select a.id,a.activityid,b.status 
   from tbl_activities a 
   inner join tbl_sub_activities b on a.id=b.activityid 
   Group by a.id order by b.status DESC

答案 2 :(得分:1)

为了更好:

SELECT
    a.id,
    a.activity,
    case when SUM(s.status = "done") = count(s.status)
         then "DONE" else "ONGOING" 
    END
FROM tbl_activities a
INNER JOIN tbl_sub_activities s ON s.activityId = a.id
GROUP BY a.id;