SQL查询优化 - 替代方式

问题描述:

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" 

通常我们,'三计数查询'或'三国单个查询'中的子查询。

有没有更好的方法,我可以在单个查询中获取动作类型的计数?

使用条件汇总:

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