我正在尝试编写一个查询,根据今天的日期计算行的SUMS和总条目。我的数据库中的日期字段是03/14/2012 2:03:19格式。该查询忽略日期并返回数据库中所有条目的SUM。这是我的疑问:
$string = "
SELECT SUM(totalcollected)
FROM accounting
WHERE agent = '$agentid'
AND DATE(date) = DATE(NOW())
AND amount1type = 'Cash'
OR amount2type = 'Cash'
";
有什么建议吗?
答案 0 :(得分:3)
看看MySQL Operator Precedence chart。您会注意到AND
与OR
相比具有更高的优先级,因此您的查询会变为:
SELECT SUM(totalcollected)
FROM accounting
WHERE
(
agent = '$agentid' AND
DATE(DATE) = DATE(NOW()) AND
amount1type = 'Cash'
)
OR
(
amount2type = 'Cash'
)
请注意,当(i)代理人= $代理人(ii)amount1type = cash时,会考虑日期;但是无论日期如何,都将返回具有amount2type = cash的行。你应该添加括号来告诉MySQL究竟应该如何处理where子句:
SELECT SUM(totalcollected)
FROM accounting
WHERE
agent = '$agentid' AND
DATE(DATE) = DATE(NOW()) AND
(
amount1type = 'Cash' OR amount2type = 'Cash'
)
答案 1 :(得分:2)
我的猜测是你在where
条款中遗漏了一些问题......
最终条件or amount2type = 'cash'
允许其他所有条件都为假。您应该将其更改为与amount1type
:
SELECT SUM(amount1), SUM(amount2), SUM(monpay), SUM(totalcollected)
FROM accounting
WHERE
agent = '$agentid'
AND DATE(date) = DATE(NOW())
AND (amount1type = 'Cash' OR amount2type = 'Cash')
答案 2 :(得分:1)
问题是AND
在 OR
之前解析了,但你可以完全避免OR
这个很酷的伎俩:
SELECT SUM(totalcollected)
FROM accounting
WHERE agent = '$agentid'
AND DATE(date) = DATE(NOW())
AND 'Cash' IN (amount1type, amount2type)
答案 3 :(得分:0)
您需要使用括号来向数据库表示您实际尝试执行的操作。更好的格式化将使其更清晰
SELECT SUM(totalcollected)
FROM accounting
WHERE agent = '$agentid'
AND DATE(date) = DATE(NOW())
AND amount1type = 'Cash'
OR amount2type = 'Cash'
与
SELECT SUM(totalcollected)
FROM accounting
WHERE agent = '$agentid'
AND DATE(date) = DATE(NOW())
AND (amount1type = 'Cash' OR amount2type = 'Cash')