当前位置: 移动技术网 > IT编程>数据库>Mysql > mysql使用from与join两表查询的区别总结

mysql使用from与join两表查询的区别总结

2019年01月04日  | 移动技术网IT编程  | 我要评论
前言 在mysql中,多表连接查询是很常见的需求,在使用多表查询时,可以from多个表,也可以使用join连接连个表 这两种查询有什么区别?哪种查询的效率更

前言

在mysql中,多表连接查询是很常见的需求,在使用多表查询时,可以from多个表,也可以使用join连接连个表

这两种查询有什么区别?哪种查询的效率更高呢? 带着这些疑问,决定动手试试

1.先在本地的mysql上先建两个表one和two

one表

create table `one` (
 `id` int(0) not null auto_increment,
 `one` varchar(100) not null,
 primary key (`id`)
) engine = innodb character set = utf8;

two表

create table `two` (
 `id` int(0) not null auto_increment,
 `two` varchar(100) not null,
 primary key (`id`)
) engine = innodb character set = utf8;

先随便插入几条数据,查询看一下;

select one.id,one.one,two.id,two.two from one,two where one.id=two.id;

select one.id,one.one,two.id,two.two from one join two on one.id=two.id;

对比这两次的查询,查询时间几乎没有区别,查看sql运行分析,也没有区别

为了突出两种查询的性能差异,往one表中插入100w条数据,往two表中插入10w条数据,在大量数据面前,一丝一毫的差别也会被无限放大;这时候在来比较一下差异

先使用python往数据库中插入数据,为啥用python,因为python写起了简单

上代码

import pymysql

db = pymysql.connect("127.0.0.1", 'root', "123456", "bruce")
cursor = db.cursor()

sql = "insert into one (one) values (%s)"
for i in range(1000000):
 cursor.executemany(sql, ['one' + str(i)])
 if i % 10000 == 0:
 db.commit()
 print(str(i) + '次 commit')
db.commit()

print('insert one ok')
sql2 = "insert into two (two) values (%s)"
for i in range(100000):
 cursor.executemany(sql2, ['two' + str(i)])
 if i % 10000 == 0:
 db.commit()
 print(str(i) + '次 commit')
db.commit()
print('insert two ok')

耐心等待一会,插入需要一些时间;

等数据插入完成,来查询一些看看

先使用from两个表查询

select one.id,one.one,two.id,two.two from one,two where one.id=two.id;

用时大约20.49;

再用join查询看一下

select one.id,one.one,two.id,two.two from one join two on one.id=two.id;

用时19.45,在10w条数据中,1秒的误差并不算大,

查看一下使用id作为条件约束时的查询

查询时间没有差别
再看一下sql执行分析

结果还是一样的

总结

在mysql中使用from查询多表和使用join连接(left join,right join除外),查询结果,查询效率是一样的

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网