前言
在mysql中,多表連接查詢(xún)是很常見(jiàn)的需求,在使用多表查詢(xún)時(shí),可以from多個(gè)表,也可以使用join連接連個(gè)表
這兩種查詢(xún)有什么區(qū)別?哪種查詢(xún)的效率更高呢? 帶著這些疑問(wèn),決定動(dòng)手試試
1.先在本地的mysql上先建兩個(gè)表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;
先隨便插入幾條數(shù)據(jù),查詢(xún)看一下;
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;

對(duì)比這兩次的查詢(xún),查詢(xún)時(shí)間幾乎沒(méi)有區(qū)別,查看sql運(yùn)行分析,也沒(méi)有區(qū)別
為了突出兩種查詢(xún)的性能差異,往one表中插入100w條數(shù)據(jù),往two表中插入10w條數(shù)據(jù),在大量數(shù)據(jù)面前,一絲一毫的差別也會(huì)被無(wú)限放大;這時(shí)候在來(lái)比較一下差異
先使用python往數(shù)據(jù)庫(kù)中插入數(shù)據(jù),為啥用python,因?yàn)閜ython寫(xiě)起了簡(jiǎn)單
上代碼
import pymysqldb = 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')耐心等待一會(huì),插入需要一些時(shí)間;
等數(shù)據(jù)插入完成,來(lái)查詢(xún)一些看看
先使用FROM兩個(gè)表查詢(xún)
select one.id,one.one,two.id,two.two from one,two where one.id=two.id;

用時(shí)大約20.49;
再用JOIN查詢(xún)看一下
select one.id,one.one,two.id,two.two from one join two on one.id=two.id;

用時(shí)19.45,在10w條數(shù)據(jù)中,1秒的誤差并不算大,
查看一下使用id作為條件約束時(shí)的查詢(xún)


查詢(xún)時(shí)間沒(méi)有差別
再看一下sql執(zhí)行分析


結(jié)果還是一樣的
總結(jié)
在mysql中使用FROM查詢(xún)多表和使用JOIN連接(LEFT JOIN,RIGHT JOIN除外),查詢(xún)結(jié)果,查詢(xún)效率是一樣的
好了,以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)VeVb武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選