試試這個(你可以稱之爲「條件計數」 - 爲此,一個非常方便的技術):
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
和條件來獲得任意條件組合的計數 - 這使您不必進行子查詢,自連接,多個查詢等。希望它有幫助。
否。不拒絕狀態表示我想獲取包含所有未拒絕的任務的event_types。它也會生成計數,但要求是保留所有這些事件類型,但返回只是ta.status ='不完整' – Hammad
的任務計數,編輯以保留「status!='被拒絕'的原始過濾器」 – SlimsGhost
意思是如果我將ta.status!=「拒絕」改爲ta.status ='不完整'我將得到正確的任務計數,但某些event_types將通過更改狀態過濾器而被忽略。我希望兩者都......計算所有類型任務的不完整任務和event_types – Hammad