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。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值