mysql查询总和的差异

时间:2016-05-04 15:54:14

标签: mysql sql sum

我对看似相同的查询有不同的结果。我很困惑为什么总数与查询不同。希望有人对这个问题有一个解释,也许可以说哪个应该是正确的总数。谢谢

select sum(tm_hours) 
FROM bhds_timecard 
WHERE (tm_notes = 'Session' 
 OR tm_notes = 'Intake' 
 OR tm_notes = 'OT' 
 or tm_notes = 'PT' 
 or tm_notes = 'Speech') 
AND (tm_date BETWEEN '2016-04-01' AND '2016-04-30')

总计1792.25

SELECT SUM(tm_hours) 
FROM bhds_timecard 
WHERE (tm_date BETWEEN '2016-04-01' AND '2016-04-30') 
AND tm_notes = 'Session' 
OR tm_notes = 'Intake' 
OR tm_notes = 'OT' 
OR tm_notes = 'PT' 
OR tm_notes = 'Speech'

总计1796.25

5 个答案:

答案 0 :(得分:1)

如果你理解为什么5 + 3 * 2 = 11那么这将有助于理解你的问题的根源。有些人可能会错误地认为上面的计算应该给你16,因为他们不知道操作的顺序。乘法优先于加法,因此首先完成。

同样,AND的优先级高于OR,因此首先完成。查看MySQL参考手册中的Operator Precedence部分。

这可能是您尝试构建的代码:

SELECT SUM(tm_hours) 
FROM bhds_timecard 
WHERE tm_date BETWEEN '2016-04-01' AND '2016-04-30'
AND (tm_notes = 'Session' 
OR tm_notes = 'Intake' 
OR tm_notes = 'OT' 
OR tm_notes = 'PT' 
OR tm_notes = 'Speech');

在这种情况下,由于括号覆盖了标准的操作顺序,因此首先执行括号中的所有内容(所有OR语句)。因此,如果只有一个条件评估为TRUE,则整个括号部分将评估为TRUE。接下来你的所有ANDS都会得到评估,你就得到了答案。

答案 1 :(得分:0)

第二个查询必须是这样的:

SELECT SUM(tm_hours) FROM bhds_timecard WHERE (tm_date BETWEEN '2016-04-01' AND '2016-04-30') 
AND (tm_notes = 'Session' OR tm_notes = 'Intake' OR tm_notes = 'OT' OR tm_notes = 'PT' OR tm_notes = 'Speech')

您丢失了第二组条件的(括号

答案 2 :(得分:0)

第一个查询是将所有OR评估为一个条件 -

WHERE (tm_notes = 'Session' 
 OR tm_notes = 'Intake' 
 OR tm_notes = 'OT' 
 or tm_notes = 'PT' 
 or tm_notes = 'Speech')
AND (tm_date BETWEEN '2016-04-01' AND '2016-04-30')

如果某行满足任何条件,则计算为true,然后转到日期约束。所以在第一个查询中确实只有2个顶级条件。

第二个查询实际上有6个条件 -

WHERE (tm_date BETWEEN '2016-04-01' AND '2016-04-30') 
AND tm_notes = 'Session' 
OR tm_notes = 'Intake' 
OR tm_notes = 'OT' 
OR tm_notes = 'PT' 
OR tm_notes = 'Speech'

如果6个OR中的任何一个为真,则整个WHERE子句被评估为真。

答案 3 :(得分:0)

您的第一个查询条件是这样的

Where
--first condition 
(tm_notes = 'Session' OR tm_notes = 'Intake' OR tm_notes = 'OT' or tm_notes = 'PT' or tm_notes = 'Speech')
AND 
-- second condition
(tm_date BETWEEN '2016-04-01' AND '2016-04-30')

你选择两个条件都是真的,首先条件本身就是条件的组合,

虽然在第二个查询中你有OR的这么多条件,所以如果任何条件变为真,整个条件模式都会变为真,所以结果有差异

Where
-- first condition
(tm_date BETWEEN '2016-04-01' AND '2016-04-30') 
AND 
-- second condition
tm_notes = 'Session' 
OR
-- third condition 
tm_notes = 'Intake' 
OR 
-- fourth condition
tm_notes = 'OT' 
OR 
-- fifth condition
tm_notes = 'PT' 
-- sixth condition
OR 
tm_notes = 'Speech'

答案 4 :(得分:0)

AND& OR就像+& -

a+(b*c)(a+b)*c

不同

AND& OR

a OR (b AND c)(a OR b) AND c

不同

混淆AND&时,请小心使用方括号。 OR