MySQL - 哪个查询会更快

时间:2013-08-13 09:05:17

标签: mysql sql performance benchmarking

我有一个数据库(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

1 个答案:

答案 0 :(得分:0)

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