我有三张桌子:
有一个奇怪的要求:
我希望所有按其event_type分组的tasks_assignments都包含每个event_type中的任务计数。
问题是我想要获取所有事件类型,但只计算不完整的任务。
这是我的问题:
select *,count(t.id) as total
from event_type et,
task t,
task_assignment ta
where et.id = t.event_type_id
and ta.task_id = t.id
AND ta.assignee_id=" . $user_id . "
AND ta.status!='Rejected'
group by t.event_type_id
order by total desc limit " . $limit . " offset ".$offset
我该怎么办?
答案 0 :(得分:1)
试试这个(你可以称之为"条件计数" - 一个非常方便的技术用于此目的):
select t.event_type_id,
count(t.id) as total,
sum(case when ta.status = 'Incomplete' then 1 else 0 end) as total_incomplete
from event_type et,
task t,
task_assignment ta
where et.id = t.event_type_id
and ta.task_id = t.id
AND ta.assignee_id=" . $user_id . "
AND ta.status!='Rejected'
group by t.event_type_id
order by total desc limit " . $limit . " offset ".$offset
哦,你只能选择没有聚合的字段(如count()和sum()),如果你还group by
它们,那么我将你的select *
改为select t.event_type_id
。您可以修改它以包含您需要的任何列。
根据您的评论,您可以从WHERE
条款中删除过滤器,并使用"条件计数"执行更多操作,并根据您的特定需求进行更改:
select t.event_type_id,
count(*) as total_events,
sum(case when ta.status = 'Incomplete' then 1 else 0 end) as total_incomplete,
sum(case when ta.status = 'Incomplete'
and ta.status != 'Rejected' then 1 else 0 end) as total_incomplete_not_rejected
sum(case when ta.status != 'Rejected' then 1 else 0 end) as total_not_rejected
from event_type et,
task t,
task_assignment ta
where et.id = t.event_type_id
and ta.task_id = t.id
AND ta.assignee_id=" . $user_id . "
group by t.event_type_id
order by total desc limit " . $limit . " offset ".$offset
主要思想是使用SUM
和条件来获取任何条件组合的计数 - 这使您不必进行子查询,自连接,多个查询等。希望它有所帮助。