2013-10-30 89 views
1

我有一个像下面这样的mysql查询。相同(子)查询多次在一个MySQL查询

select new,processing,close 
from 

(select count(id) new from tickets where id_client in (_a_list_of_client_id) and status = new), 

(select count(id) processing from tickets where id_client in (_a_list_of_client_id) and status = processing), 

(select count(id) close from tickets where id_client in (_a_list_of_client_id) and status = close) 

以下是不准确的查询,但伪查询

这里_a_list_of_client_id就像下面从客户 选择id_client其中id_user = {some_id_given_as_parameter}

我只是想知道是另一个查询这是在查询中多次使用相同子查询的正确方法。或者有没有其他的方式来做这样的事情。

在此先感谢 MH RASEL

回答

1

您可以使用sumcase和移动子查询到where标准:

select 
    sum(case when status = 'new' then 1 else 0 end) new, 
    sum(case when status = 'processing' then 1 else 0 end) processing, 
    sum(case when status = 'close' then 1 else 0 end) close 
from tickets 
where id_client in (_a_list_of_client_id) 

有几个其他的方式来做到这一点(使用if例如或者忽略了case),但我认为这很容易阅读。例如,我相信mysql将与sum(status='new')一起工作。