两个表结构分别为
CREATE TABLE `t1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rid` int(11) NOT NULL,
`num` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=24236 DEFAULT CHARSET=utf8;
CREATE TABLE `t2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sid` int(11) NOT NULL,
`num` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=24287 DEFAULT CHARSET=utf8;
两个表数据都是1万条,查询10次,最短和最长用时
select t1.id,sum(t1.num) from t1 LEFT JOIN t2 on t2.id=t1.id where t2.num=2 GROUP BY t1.id;
时间: 0.007s 0.009s
select t1.id,sum(t1.num) from (select id from t2 where num =2) as t3 LEFT JOIN t1 on t3.id=t1.id GROUP BY t1.id;
时间: 0.007s 0.009s
select t1.id,sum(t1.num) from (select * from t2 where num =2) as t3 LEFT JOIN t1 on t3.id=t1.id GROUP BY t1.id;
时间: 0.005s 0.009s
select id,sum(num) from t1 where id in (select id from t2 where num =2) group by id;
时间: 0.013s 0.017s
两个表数据都是2万条,查询10次,最短和最长用时
select t1.id,sum(t1.num) from t1 LEFT JOIN t2 on t2.id=t1.id where t2.num=2 GROUP BY t1.id;
时间: 0.014s 0.023s
select t1.id,sum(t1.num) from (select id from t2 where num =2) as t3 LEFT JOIN t1 on t3.id=t1.id GROUP BY t1.id;
时间: 0.012s 0.020s
select t1.id,sum(t1.num) from (select * from t2 where num =2) as t3 LEFT JOIN t1 on t3.id=t1.id GROUP BY t1.id;
时间: 0.016s 0.017s
select id,sum(num) from t1 where id in (select id from t2 where num =2) group by id;
时间: 0.015s 0.030s
两个表数据都是10万条,查询10次,最短和最长用时
select t1.id,sum(t1.num) from t1 LEFT JOIN t2 on t2.id=t1.id where t2.num=2 GROUP BY t1.id;
时间: 0.045s 0.049s
select t1.id,sum(t1.num) from (select id from t2 where num =2) as t3 LEFT JOIN t1 on t3.id=t1.id GROUP BY t1.id;
时间: 0.042s 0.046s
select t1.id,sum(t1.num) from (select * from t2 where num =2) as t3 LEFT JOIN t1 on t3.id=t1.id GROUP BY t1.id;
时间: 0.044s 0.048s
select id,sum(num) from t1 where id in (select id from t2 where num =2) group by id;
时间: 0.045s 0.103s
总结
无一例外,用时最大值都发生在第一次查询,后面的九次效率都差不多,select in在数据量增大时,效率变得更慢。而join关联查询受影响比较小,比较稳定,数据量超过1万最好是使用join查询。
值得一提的是不用子查询的方式,join方式查询的效率依然很高,跟用子查询效率相差只有0.002s。