gpt4 book ai didi

mysql - 从子查询返回列数

转载 作者:行者123 更新时间:2023-11-29 12:01:47 24 4
gpt4 key购买 nike

我有三个表:

  1. 任务(id、task_name、event_type_id)
  2. 任务分配(id、task_id、受让人_id、分配者_id、状态)
  3. 事件类型

有一个奇怪的要求:

我想要将所有任务分配按其 event_type 以及每个 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

我应该做什么?

最佳答案

尝试一下(您可以将其称为“条件计数” - 用于此目的的一种非常方便的技术):

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()),所以我更改了您的 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 和条件来获取任意条件组合的计数 - 这使您不必执行子查询、自联接、多个查询等。希望它有帮助.

关于mysql - 从子查询返回列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32251481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com