MySQL-查询速度会更快



我有一个数据库(MySQL),其中包含有关照片、评分(人们可以投票)和评论的信息。

CREATE TABLE IF NOT EXISTS `Photos` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `Description` NVARCHAR(2000),
  `Author` INT,
  `Contest` INT,
  `PhoneModel` NVARCHAR(200),
  `PhotoThumbPath` NVARCHAR(2000),  
  `PhotoPath` NVARCHAR(2000),
  `Date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `State` INT DEFAULT 1,
  FOREIGN KEY (`Author`) REFERENCES `Users`(`ID`), 
  FOREIGN KEY (`Contest`) REFERENCES `Contests`(`ID`), 
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `PhotoComments` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `Author` INT,
  `Photo` INT,
  `Comment` NVARCHAR(2000),
  `Date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `ReplyTo` INT,
  FOREIGN KEY (`Author`) REFERENCES `Users`(`ID`), 
  FOREIGN KEY (`Photo`) REFERENCES `Contests`(`ID`), 
  FOREIGN KEY (`ReplyTo`) REFERENCES `PhotoComments`(`ID`), 
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `PhotoComments` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `Author` INT,
  `Photo` INT,
  `Comment` NVARCHAR(2000),
  `Date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `ReplyTo` INT,
  FOREIGN KEY (`Author`) REFERENCES `Users`(`ID`), 
  FOREIGN KEY (`Photo`) REFERENCES `Contests`(`ID`), 
  FOREIGN KEY (`ReplyTo`) REFERENCES `PhotoComments`(`ID`), 
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

现在我想向数据库索取一张确定的照片,告诉我它有多少评论,有多少评级,平均评级是多少。

以下哪种方式会更快:带子查询的查询3:

SELECT P.PhotoPath, P.Date, P.PhoneModel,
(SELECT COUNT(1) FROM PhotoComments C where C.Photo=P.ID) as CommentsCount,
(SELECT COUNT(1) FROM PhotoRatings R where R.Photo=P.ID) as RatingsCount,
(SELECT COALESCE(AVG(Rating), 0) FROM PhotoRatings R where R.Photo=P.ID) as RatingsAvg 
FROM Photos WHERE P.ID=$photoID

或者一个有2个左联接的大查询:

SELECT P.PhotoPath, P.Date, P.PhoneModel,
COUNT(DISTINCT C.ID) as CommentsCount,
COUNT(DISTINCT R.ID) as RatingsCount,
COALESCE(AVG(R.Rating), 0) as RatingsAvg
FROM Photos P
LEFT JOIN PhotoComments C ON C.Photo=P.ID
LEFT JOIN PhotoRatings R ON R.Photo=P.ID
WHERE P.ID=$photoID
GROUP BY P.ID

在查询中使用EXPLAIN,并比较结果

相关内容

  • 没有找到相关文章

最新更新