sql - MySQL - which query will be faster -


i have database (mysql) contains information photos, ratings (people can vote) , comments.

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 ; 

now want ask database certaing photo give me how many comments has, how many ratings , what's average rating.

which 1 of ways faster: query subqueries 3:

select p.photopath, p.date, p.phonemodel, (select count(1) photocomments c c.photo=p.id) commentscount, (select count(1) photoratings r r.photo=p.id) ratingscount, (select coalesce(avg(rating), 0) photoratings r r.photo=p.id) ratingsavg  photos p.id=$photoid 

or 1 big query 2 left joins:

select p.photopath, p.date, p.phonemodel, count(distinct c.id) commentscount, count(distinct r.id) ratingscount, coalesce(avg(r.rating), 0) ratingsavg photos p left join photocomments c on c.photo=p.id left join photoratings r on r.photo=p.id p.id=$photoid group p.id 

use explain on querys, , compare result


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -