2013-10-30 87 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')一起工作。