2014-12-13 68 views
-1

enter image description hereSQL查詢優化 - 替代方式

我需要填補這一變量對給定action_to(包含用戶ID)

type_1_count = "select count(action_type) from action where action_type = 1 AND user_from = 13213" 

type_2_count = "select count(action_type) from action where action_type = 2 AND user_from = 13213" 

type_3_count = "select count(action_type) from action where action_type = 3 AND user_from = 13213" 

$type_counts = "three count sub queries in single query" 

通常我們,'三計數查詢'或'三國單個查詢'中的子查詢。

有沒有更好的方法,我可以在單個查詢中獲取動作類型的計數?

回答

3

使用條件彙總:

select sum(action_type = 1) as type_1_count, 
     sum(action_type = 2) as type_2_count, 
     sum(action_type = 3) as type_3_count  
from action 
where user_from = 13213; 

或者,使用group by

select action_type, count(*) as cnt 
from action 
where user_from = 13213; 

不同的是,第一個查詢生成一行與不同的計數。第二行在數據中每action_type產生一行,計數作爲第二列。

編輯:

表達sum(action_type = 3)計數其中action_type具有3.在MySQL的值的行數,布爾值被視爲整數在數值上下文,與真正的爲1,假爲0,所以, sum(action_type = 3)統計action_type在該值上的行數。

+0

'SUM'是否可以作爲划船計數法使用? – 2014-12-13 13:47:14

+0

@SamuelCook。 。 。當然。 'sum(1)'和'count(*)'做同樣的事情。 – 2014-12-13 13:47:56

+0

但是如果'action_type' = 3會怎麼樣?每行不會被計算3次? – 2014-12-13 13:49:27