SQL Query产生错误的计数结果

时间:2013-04-10 18:49:35

标签: mysql sql

我有以下SQL查询

SELECT
  DISTINCT
  count("SiteTree_Live"."ID") 
FROM  
  "SiteTree_Live"
  LEFT JOIN "Page_Live" ON "Page_Live"."ID" = "SiteTree_Live"."ID"
  LEFT JOIN "TourPage_Live" ON "TourPage_Live"."ID" = "SiteTree_Live"."ID"
  LEFT JOIN "DepartureDate" ON "DepartureDate"."TourID" = "SiteTree_Live"."ID"
WHERE 
  ("SiteTree_Live"."Locale" = 'en_AU')
  AND ("SiteTree_Live"."ClassName" IN ('TourPage'))
  AND ("DepartureDate"."DepartureDate" LIKE '2012-11%')

但它产生错误的计数作为查询结果。此查询假设要返回的总意图结果不应超过245,但目前,其返回的结果大于“4569”。

这是因为“DepartureDate”表上的JOIN,因为当我从“DepartureDate”表中删除连接时,查询返回预期结果。

我需要对查询进行哪些修改才能计算“SiteTree_Live”,“ID”和“DepartureDate”之间的Macthes。“TourID”只计算“SiteTree_Live”。“ID”计数不包括出发日期?

欢迎任何建议:)

回答

SELECT 
COUNT(DISTINCT SiteTree_Live.ID) 
FROM 
"SiteTree_Live" LEFT JOIN "Page_Live" ON "Page_Live"."ID" = "SiteTree_Live"."ID" 
LEFT JOIN "TourPage_Live" ON "TourPage_Live"."ID" = "SiteTree_Live"."ID" 
LEFT JOIN "DepartureDate" ON "DepartureDate"."TourID" = "SiteTree_Live"."ID" 
WHERE 
("SiteTree_Live"."Locale" = 'en_AU') 
AND ("SiteTree_Live"."ClassName" IN ('TourPage'))
AND ("DepartureDate"."DepartureDate" LIKE '2013-03%')

似乎给了我正确的结果。感谢提示@Michael Berkowski

2 个答案:

答案 0 :(得分:1)

这样做(你有一堆不需要的连接)

SELECT 
  COUNT(DISTINCT SiteTree_Live.ID) 
FROM 
  `SiteTree_Live`
LEFT JOIN 
  `DepartureDate` ON `DepartureDate`.`TourID` = `SiteTree_Live`.`ID` 
WHERE 
  `SiteTree_Live`.`Locale` = 'en_AU'
  AND `SiteTree_Live`.`ClassName` = 'TourPage'
  AND `DepartureDate`.`DepartureDate` LIKE '2013-03%'

您也可以进行GROUP BY:

SELECT 
  COUNT(SiteTree_Live.ID) 
FROM 
  `SiteTree_Live`
LEFT JOIN 
  `DepartureDate` ON `DepartureDate`.`TourID` = `SiteTree_Live`.`ID` 
WHERE 
  `SiteTree_Live`.`Locale` = 'en_AU'
  AND `SiteTree_Live`.`ClassName` = 'TourPage'
  AND `DepartureDate`.`DepartureDate` LIKE '2013-03%'
GROUP BY
  SiteTree_Live.ID

答案 1 :(得分:1)

次要更正:如果DepartureDate是日期类型,那么LIKE '2013-03%将强制它被强制转换为字符类型(这是一个mysql 功能)As结果,DepartureDate上的任何索引都不会被使用,IIRC。更好地使用普通范围查询:

SELECT 
  COUNT(DISTINCT stl.ID) 
FROM 
  SiteTree_Live stl
LEFT JOIN 
  DepartureDate dd ON dd.TourID = stl.ID 
WHERE 
  stl.Locale = 'en_AU'
  AND stl.ClassName = 'TourPage'
  AND dd.DepartureDate >= '2013-03-01'
  AND dd.DepartureDate < '2013-04-01'
   ;