1. 程式人生 > 資料庫 >mysql使用from與join兩表查詢的區別總結

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,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,255); text-indent: 0px; font-variant-ligatures: normal; font-variant-caps: normal; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial" src="http://img.cppcns.com/pic.php?url=/file_images/article/201812/20181230132614454.jpg?20181130132634" />

用時大約20.49;

再用JOIN查詢看一下

select one.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除外),查詢結果,查詢效率是一樣的

好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對我們的支援。