我有两个查询需要在一个查询上:
SELECT call_queues.queue_alias, count(users.*) as free
FROM call_queues
INNER JOIN call_queues_users ON call_queues.id = call_queues_users.call_queue_id
INNER JOIN users ON call_queues_users.user_id = users.id
WHERE users.phone_status_id = 0
AND users.status_id = 1
GROUP BY call_queues.queue_alias
该查询返回如下内容:
queue_alias | free
---------------------+---------------
Teste Rodolfo | 1
Teste Diego | 1
Desenvolvimento | 1
Suporte Emergencial | 1
Gestores | 1
还有一个:
SELECT call_queues.queue_alias, count(users.*) as disconnected
FROM call_queues
INNER JOIN call_queues_users ON call_queues.id = call_queues_users.call_queue_id
INNER JOIN users ON call_queues_users.user_id = users.id
WHERE users.phone_status_id = 4
AND users.status_id <> 2
GROUP BY call_queues.queue_alias
返回:
queue_alias | disconnected
----------------------+--------------
Comercial Emergencia | 1
Comercial | 1
Comunicação | 1
Testes Flawbson | 1
当我在一个选择中加入这两个查询时:
SELECT
( SELECT COUNT(users.*)
FROM call_queues
INNER JOIN call_queues_users ON call_queues.id = call_queues_users.call_queue_id
INNER JOIN users ON call_queues_users.user_id = users.id
WHERE users.phone_status_id = 0
AND users.status_id = 1
GROUP BY call_queues.queue_alias) AS free,
(SELECT count(users.*)
FROM call_queues
INNER JOIN call_queues_users ON call_queues.id = call_queues_users.call_queue_id
INNER JOIN users ON call_queues_users.user_id = users.id
WHERE users.phone_status_id = 4
AND users.status_id <> 2
GROUP BY call_queues.queue_alias) AS disconnected;
我在标题中收到了错误消息。
我认为问题是查询返回不同的行数。
查询结果应为:
queue_alias | disconnected | free
----------------------+--------------+---------
Comercial Emergencia | 1 | 0
Comercial | 1 | 0
Comunicação | 1 | 0
Testes Flawbson | 1 | 0
Teste Rodolfo | 0 | 1
Teste Diego | 0 | 1
Desenvolvimento | 0 | 1
Suporte Emergencial | 0 | 1
Gestores | 0 | 1
那么,如果错误信息与我的想法无关,我如何在db中执行上述结果?
答案 0 :(得分:2)
您的查询不起作用,因为子查询中有group by
。因此,在许多情况下,子查询将返回多行。
相反,使用条件聚合:
SELECT q.queue_alias,
SUM(CASE WHEN u.phone_status_id = 0 AND u.status_id = 1 THEN 1 ELSE 0 END) as free,
SUM(CASE WHEN u.phone_status_id = 4 AND u.status_id <> 2 THEN 1 ELSE 0 END) as disconnected
FROM call_queues q INNER JOIN
call_queues_users qu
ON q.id = qu.call_queue_id INNER JOIN
users u
ON cq.user_id = users.id
GROUP BY q.queue_alias;