mysql计数显示比预期更多的结果

时间:2013-04-03 14:47:30

标签: mysql

这是我的问题:

SELECT COUNT(*) FROM jos_mls AS mls 
    INNER JOIN jos_activeagents AS active ON active.AGENTUID = mls.MSTLISTBRD
    AND mls.MSTACTSTA = 'Active' OR mls.MSTACTSTA = 'Keep Showing';

这些表非常大,因此很难显示表结构。

当我在没有AND mls.MSTACTSTA = 'Active' OR mls.MSTACTSTA = 'Keep Showing'的情况下运行计数时,我得到了预期的结果(大约500)。但是,当我想用​​这些参数过滤掉它时,它会重新获得25000+个结果,当它应该低于500时。

我认为这是一个语法问题,但查找类似的问题,我无法提出解决方案。

3 个答案:

答案 0 :(得分:0)

使用WHERE子句

SELECT COUNT(*) FROM jos_mls AS mls 
    INNER JOIN jos_activeagents AS active ON active.AGENTUID = mls.MSTLISTBRD
    WHERE mls.MSTACTSTA = 'Active' OR mls.MSTACTSTA = 'Keep Showing';

答案 1 :(得分:0)

SELECT COUNT(*) 
  FROM jos_mls mls 
  JOIN jos_activeagents active 
    ON active.AGENTUID = mls.MSTLISTBRD
   AND (mls.MSTACTSTA = 'Active' OR mls.MSTACTSTA = 'Keep Showing');

SELECT COUNT(*) 
  FROM jos_mls mls 
  JOIN jos_activeagents active 
    ON active.AGENTUID = mls.MSTLISTBRD
   AND mls.MSTACTSTA IN('Active','Keep Showing');

答案 2 :(得分:0)

AND优先于OR,因此您应该在条件的第二部分周围使用括号来获得所需的输出:

SELECT COUNT(*) FROM jos_mls AS mls 
    INNER JOIN jos_activeagents AS active ON active.AGENTUID = mls.MSTLISTBRD
    AND (mls.MSTACTSTA = 'Active' OR mls.MSTACTSTA = 'Keep Showing');

您获得的行数远远超出预期的原因是您运行的实际查询与此相同:

SELECT COUNT(*) FROM jos_mls AS mls 
    INNER JOIN jos_activeagents AS active ON (active.AGENTUID = mls.MSTLISTBRD
    AND mls.MSTACTSTA = 'Active') OR mls.MSTACTSTA = 'Keep Showing';