0

好吧,我放弃了,这个问题已经超出了我的想象,我正在寻求帮助。

在 MySQL 数据库中,我有一个类别和一个帖子表,就像标准的博客系统一样:

tblCategories (intID (PK), strTitle)
tblAreas (intID (PK), strName)
tblPosts (intID (PK), intCategoryID (FK), strTitle, htmlText)

然后我有几个博客支持表:

tblExternalLinks (intID (PK), intPostID (FK), strTitle, urlLink)
tblComments (intID (PK), intPostID (FK), strComment)
tblImages (intID (PK), intPostID (FK), urlImage)
tblLocations (intID (PK), intPostID (FK), intAreaID (FK), urlImage)
  1. 我想要一个附加到类别变量的所有帖子的列表(我们只是在伪 php 代码中说)$intCatID,并且它的位置具有某个区域变量 $intAreaID。这个 SQL 应该是这样的:

    SELECT tblPosts.* from tblPosts 
    INNER JOIN tblLocations ON tblLocations.intPostID=tblPosts.intID 
    WHERE intCategoryID=$intCatID AND intAreaID=$intAreaID GROUP BY tblPosts.intID;
    

    有人可以让我知道这是否正确吗?我不确定 GROUP BY 部分。

  2. 我想要相同的列表,但这次是支持表中所有其他附加记录的计数:

    SELECT tblPosts.*, intExternalLinksCount, intCommentsCount, intImagesCount, intLocationsCount ...
    

    我的第一个猜测是使用嵌套表或连接检索计数,这可能会使查询变得非常大。我也想知道什么是更快的性能。这些东西是我头疼的地方。

并高度赞赏答案...

4

1 回答 1

0

只是因为我很想收到批评性的反馈,所以我想出了这个(非常非常丑陋的)查询:

SELECT 
tblPosts.*, 
tblTempLocations.intLocationsCount, 
tblTempLinks.intLinksCount, 
tblTempImages.intImagesCount, 
tblTempComments.intCommentsCount,
tblTempNearest.fltNearestLocationAngle
FROM tblAdverts 
LEFT JOIN 
 (SELECT intPostID, count(*) as intLocationsCount 
  FROM tblLocations 
  GROUP BY intPostID)
 tblTempLocations ON tblPosts.intID=tblTempLocations.intPostID
LEFT JOIN 
 (SELECT intPostID, count(*) as intLinksCount 
  FROM tblLinks 
  GROUP BY intPostID)
 tblTempLinks ON tblPosts.intID=tblTempLinks.intPostID
LEFT JOIN 
 (SELECT intPostID, count(*) as intImagesCount
  FROM tblImages
  GROUP BY intPostID)
 tblTempImages ON tblPosts.intID=tblTempImages.intPostID
LEFT JOIN 
 (SELECT intPostID, count(*) as intReviewsCount 
  FROM tblComments
  GROUP BY intPostID)
 tblTempComments ON tblPosts.intID=tblTempComments.intPostID
LEFT JOIN
 (SELECT intPostID, 
  MIN(SQRT(POWER((fltLatitude - $fltCurrentLatitude), 2) + POWER((fltLongitude - $fltCurrentLongitude),2))) AS fltNearestLocationAngle 
  FROM tblLocations 
  GROUP BY intPostID) 
 tblTempNearest ON tblPosts.intID=tblTempNearest.intPostID
INNER JOIN tblLocations ON tblPosts.intID=tblLocations.intPostID
WHERE tblLocations.intLocationID=$intAreaID  AND tblPosts.strTitle LIKE '%$strPartialTitle%' AND tblAdverts.intCategoryID=$intCatID
GROUP BY tblAdverts.intID
于 2013-03-27T00:34:26.113 回答