2

我有以下 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”。“TourID”之间的 Macthes,而仅计算“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 的提示

4

2 回答 2

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
于 2013-04-10T19:25:32.520 回答
1

次要更正:如果DepartureDate是日期类型,LIKE '2013-03%则将强制将其强制转换为字符类型(这是 mysql功能)因此,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'
   ;
于 2013-04-10T19:35:42.167 回答