什么是最好的"在MYSQL中使用单个查询获得3个不同SUM的方法

时间:2015-06-11 09:42:03

标签: php mysql sql

这似乎是主观的,但不是。

假设:

Table with the ff. field:

 - userid
 - breakstart
 - breakend
 - minutes
 - breaktype

目标: 获取特定SUM()的每种类型中断的user,包括breakstartbreakend

到目前为止我做了什么: 我能想到的最简单的是做3个单独的查询,就像这样......

SELECT SUM(minutes) as totalbreak 
FROM `breaklog`
WHERE
    userid = <some userid>
      AND
    DATE(breakstart) = "2015-06-11"
      AND
    DATE(breakend) = "2015-06-11"
        AND
    breaktype = "1"
# just feed breaktype with valid types i.e. ("1", "2", "3")

我只是想知道是否有更好的方法来实现我的目标,可能只需要一个查询?或者甚至可能吗?或者最好是获取ALL breaktypes并在SQL引擎之外进行过滤,顺便说一下,在后端使用PHP。

提前感谢所有输入。

2 个答案:

答案 0 :(得分:2)

执行GROUP BY

SELECT breaktype, SUM(minutes) as totalbreak 
FROM `breaklog`
WHERE
    userid = <some userid>
      AND
    DATE(breakstart) = "2015-06-11"
      AND
    DATE(breakend) = "2015-06-11"
        AND
    breaktype IN ("1", "2", "3")
group by breaktype

答案 1 :(得分:2)

你也可以尝试使用分组

SELECT breaktype, SUM(minutes) as totalbreak 
FROM breaklog
WHERE
    userid = <some userid>
      AND
    DATE(breakstart) = "2015-06-11"
      AND
    DATE(breakend) = "2015-06-11"
group by breaktype
Having breaktype IN (1, 2,3)