我正在使用此查询
select t.task_id,td.task_detail_id ,
(SELECT COUNT(1) FROM task_detail tdd where tdd.task_id=t.task_id and
tdd.status='ACTIVE' ) as total
from task t inner join task_detail td on td.task_id=t.task_id
where td.task_id=t.task_id and td.status='ACTIVE' ;
查询正在以预期的结果运行,但是我想将total column
子查询更改为联接。
答案 0 :(得分:0)
请您试试这个-
SELECT
t.task_id,
td.task_detail_id,
COUNT(*)
FROM task t
INNER JOIN task_detail td
ON td.task_id = t.task_id AND td.STATUS = 'ACTIVE'
GROUP BY t.task_id, td.task_detail_id
答案 1 :(得分:0)
在MySQL 8+中,您将使用窗口函数
select t.task_id, td.task_detail_id,
count(*) over (partition by t.task_id) as total
from task t inner join
task_detail td
on td.task_id = t.task_id
where td.status = 'ACTIVE' ;
在早期版本中,建议使用子查询,但是您可以将其移动到from
子句:
select t.task_id, td.task_detail_id,
td2.total
from task t inner join
task_detail td
on td.task_id = t.task_id join
(select count(*) as total
from task_detail td2
where td2.status = 'ACTIVE'
group by td2.task_id
) td2
on td2.task_id = td.task_id
where td.status = 'ACTIVE' ;