select in與left join效率比較

兩個表結構分別爲

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。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章