【问题标题】:Two MySQL queries giving different results两个 MySQL 查询给出不同的结果
【发布时间】:2013-06-01 14:13:51
【问题描述】:

我正在运行这两个查询。第一个有效,但由于某种原因,EXISTS() 函数似乎增加了大约一分钟的加载时间,这使得它难以使用。所以我写了第二个查询,我觉得应该给出相同的答案,但它给出了一个非常不同的答案。

第一

select 
count(`FavoritesHeaderID`) `count` 
from `favoritesheader` 
join `vwactiveevent` on `vwactiveevent`.`MainEventID`=`favoritesheader`.`MainEventID` 
where `Admin`=0 
and exists(
select 1 
from `invoiceheader` 
join `vwactiveevent` on `vwactiveevent`.`MainEventID`=`invoiceheader`.`MainEventID` 
where `Phone`=`favoritesheader`.`CellPhone` 
and `OrderStatusID`=2
); => 284

第二

select 
count(`FavoritesHeaderID`) `count`
from `favoritesheader` 
join `vwactiveevent` on `vwactiveevent`.`MainEventID`=`favoritesheader`.`MainEventID`
join  `invoiceheader` on `vwactiveevent`.`MainEventID`=`invoiceheader`.`MainEventID` 
where `Admin`=0 
and `Phone`=`favoritesheader`.`CellPhone` 
and `OrderStatusID`=2; => 1578

我不知道这是否足以提供足够的信息,但如果是的话,任何帮助将不胜感激。

【问题讨论】:

  • 结果有何不同?

标签: mysql join exists


【解决方案1】:

JOIN 有可能在您的COUNT 中包含重复的行。如果我正确理解您的问题,假设 FavoritesHeaderID 是唯一的并且这是您尝试 COUNT 的字段,您可以将 DISTINCT 添加到每个查询中,它们应该返回相同的计数:

select 
    count(distinct `FavoritesHeaderID`) `count`
from `favoritesheader` 
    join `vwactiveevent` on `vwactiveevent`.`MainEventID`=`favoritesheader`.`MainEventID`
    join  `invoiceheader` on `vwactiveevent`.`MainEventID`=`invoiceheader`.`MainEventID` 
where `Admin`=0 
    and `Phone`=`favoritesheader`.`CellPhone` 
    and `OrderStatusID`=2

【讨论】:

  • 你肯定知道你的东西,尤其是当我第一次发布这个时,我在问题中缺少信息。谢谢
  • @stumpx -- np,很高兴我能帮上忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 1970-01-01
  • 2014-06-18
  • 1970-01-01
  • 2011-01-14
  • 1970-01-01
相关资源
最近更新 更多