我有一个电话呼叫数据库,它有一个字段'方向',在呼叫指示后正确命名(在OR输出中)。我的问题是,当我搜索“输入”或“输出”呼叫时,这个数字是完全错误的。
示例:
五月,
总呼叫(输入+输出):13622
IN电话:12637
OUT电话:985
SELECT `start`, `direction`, `ref_id`
FROM `call_list`
WHERE `did` = 'xxxx'
AND `start` >= '2013-05-01 00:00:00'
AND `start` < '2013-06-01 00:00:00'
以上是基于将上述查询转储到CSV并实际查看列表的准确计数。但是,当我添加“方向”搜索时,返回的数字完全关闭:
SELECT `start`, `direction`, `ref_id`
FROM `call_list`
WHERE `did` = 'xxxx'
AND `start` >= '2013-05-01 00:00:00'
AND `start` < '2013-06-01 00:00:00'
AND `direction` = 'In'
...将导致总计13461,
SELECT `start`, `direction`, `ref_id`
FROM `call_list`
WHERE `did` = 'xxxx'
AND `start` >= '2013-05-01 00:00:00'
AND `start` < '2013-06-01 00:00:00'
AND `direction` = 'Out'
..总计数为11018.
因此,如果我分组:
SELECT `direction`, count(*)
FROM `call_list`
WHERE `did` = 'xxxx'
AND `start` >= '2013-05-01 00:00:00'
AND `start` < '2013-06-01 00:00:00'
GROUP BY `direction`
...我得到了正确的计数,除非有时我需要分别对'In'或'Out'计数运行查询,因此我的数字已关闭。
'direction'列是varchar(3)utf8_unicode_ci。
如果有人能说明为什么我会收到屁计数,我真的很感激。
提前致谢
答案 0 :(得分:2)
一个疯狂的猜测但是获得比预期更多或更少行的常见原因之一是在OR
条件中使用WHERE
s而没有正确的括号
E.g。
SELECT `start`, `direction`, `ref_id`
FROM `call_list`
WHERE `did` = 'xxxx' OR `did` = 'yyyy' -- << here is the problem !!!
AND `start` >= '2013-05-01 00:00:00'
AND `start` < '2013-06-01 00:00:00'
AND `direction` = 'In'
应该是
SELECT `start`, `direction`, `ref_id`
FROM `call_list`
WHERE (`did` = 'xxxx' OR `did` = 'yyyy')
AND `start` >= '2013-05-01 00:00:00'
AND `start` < '2013-06-01 00:00:00'
AND `direction` = 'In'
这是 SQLFiddle 演示