鍍金池/ 問(wèn)答/PHP  數(shù)據(jù)庫(kù)/ mysql多表聯(lián)查 sql語(yǔ)句的的疑惑

mysql多表聯(lián)查 sql語(yǔ)句的的疑惑

多表聯(lián)查寫法一
SELECT *
FROM theme
LEFT JOIN image
ON theme.head_img_id=image.id
where theme.id='1"

多表聯(lián)查寫法二
select *
from theme,image
where theme.head_img_id=image.id
AND theme.id='1'

請(qǐng)問(wèn)下,寫法一left 還有...join、right join、inner join這些寫法與直接用select多個(gè)表有什么區(qū)別嗎?
感覺(jué)select多個(gè)表的sql寫法似乎更加方便便捷?

回答
編輯回答
半心人

關(guān)于join, cross join, inner join官方相關(guān)描述:

In MySQL, JOIN, CROSS JOIN, and INNER JOIN are syntactic equivalents (they can replace each other). In standard SQL, they are not equivalent. INNER JOIN is used with an ON clause, CROSS JOIN is used otherwise.

大意:join, cross join, inner join句法是等價(jià)的,但僅僅是當(dāng)inner join沒(méi)有使用on的時(shí)候,否則就是cross join(交叉連接)

再說(shuō),(逗號(hào))操作符,它在語(yǔ)義上也等價(jià)于inner join,回到你的問(wèn)題,select多個(gè)表(也就是逗號(hào)分割表名)是等同于join的,例如以下是等價(jià)的:

select * from t1,t2

等價(jià)

select * from t1 join t2

再一個(gè)例子:

select * from t1,t2 where t1.id=t2.id

等價(jià)

select * from t1 inner join t2 on t1.id=t2.id

但是,真要說(shuō)區(qū)別,就是,(逗號(hào))比其它任何一個(gè)join的優(yōu)先級(jí)都要低,尤其在混合,和join的sql語(yǔ)句中。例如:

select * from t1, t2 JOIN t3

等價(jià)于

select * from t1,(t2 join t3)

而不是

select * from (t1, t2) join t3

所以如果不注意這個(gè)差異,容易踩坑,以上內(nèi)容大致都來(lái)源于mysql手冊(cè)的join章節(jié),建議樓主至少看三遍以上,鏈接:https://dev.mysql.com/doc/ref...

2018年9月14日 05:16
編輯回答
離觴

只要確保使用了合適的索引,join是很快的,一次sql執(zhí)行和多次sql執(zhí)行你說(shuō)那個(gè)更快?

2018年9月6日 00:14