select in與left join效率比較

來源:互聯網
上載者:User
兩個表結構分別為
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。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.