给出两个表,一个用于工人,一个用于工人完成的任务,
CREATE TABLE IF NOT EXISTS `workers` (
`id` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `workers` (`id`) VALUES
(1);
CREATE TABLE IF NOT EXISTS `tasks` (
`id` int(11) NOT NULL,
`worker_id` int(11) NOT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `tasks` (`id`, `worker_id`, `status`) VALUES
(1, 1, 1),
(2, 1, 1),
(3, 1, 2),
(4, 1, 2),
(5, 1, 2);
我正在尝试获取每个工作人员拥有的每个状态代码的任务数量。
我可以说
SELECT w.*
,COUNT(t1.worker_id) as status_1_count
FROM workers w
LEFT JOIN tasks t1 ON w.id = t1.worker_id AND t1.status = 1
WHERE 1
GROUP BY
t1.worker_id
ORDER BY w.id
或
SELECT w.*
,COUNT(t2.worker_id) as status_2_count
FROM workers w
LEFT JOIN tasks t2 ON w.id = t2.worker_id AND t2.status = 2
WHERE 1
GROUP BY
t2.worker_id
ORDER BY w.id
并获取具有单个给定状态代码的任务数量,但是当我尝试在单个查询中获取多个任务状态的计数时,它不起作用!
SELECT w.*
,COUNT(t1.worker_id) as status_1_count
,COUNT(t2.worker_id) as status_2_count
FROM workers w
LEFT JOIN tasks t1 ON w.id = t1.worker_id AND t1.status = 1
LEFT JOIN tasks t2 ON w.id = t2.worker_id AND t2.status = 2
WHERE 1
GROUP BY t1.worker_id
,t2.worker_id
ORDER BY w.id
如果我不愿意,那么任务表就会交叉加入自身!
有没有办法将这两个查询合并为一个,以便我们可以在一个查询中检索多个任务状态的计数?
谢谢!
答案 0 :(得分:4)
SELECT w.*,
SUM(t1.status = 1) AS status_1_count,
SUM(t1.status = 2) AS status_2_count
FROM workers w
LEFT JOIN tasks t1 ON w.id = t1.worker_id AND t1.status IN (1, 2)
GROUP BY w.id
ORDER BY w.id;
答案 1 :(得分:2)
我正在尝试获取每个工作人员拥有的每个状态代码的任务数量。
SELECT worker_id, status, COUNT(*)
FROM tasks
GROUP BY worker_id, status;
就是这样。
答案 2 :(得分:0)
我这里没有MySQL的实例,但是我在t-sql框上测试了它并且它有效。
select distinct(worker_id),
(select count(*) from tasks where status = 1) as Status1,
(select count(*) from tasks where status = 2) as Status2
from tasks;