SQL查询优化 - 替代方法

时间:2014-12-13 13:43:02

标签: mysql mysqli

enter image description here

我需要为给定的 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"

通常我们会这样做,“三次查询”或“三次查询单次查询”。

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

1 个答案:

答案 0 :(得分: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中,布尔值在数值上下文中被视为整数,其中true为1,false为0。 ,sum(action_type = 3)计算action_type占用该值的行数。