SQL 語(yǔ)句的解析過程
二、FROM子句
FROM子句標(biāo)識(shí)了需要查詢的表,如果指定了表操作,會(huì)從左到右的處理,每一個(gè)基于一個(gè)或者兩個(gè)表的表操作都會(huì)返回一個(gè)輸出表。左邊表的輸出結(jié)果會(huì)作為下一個(gè)表操作的輸入結(jié)果。例如,交表相關(guān)的操作有 (1-J1)笛卡爾積,(1-J2)ON過濾器,(1-J3)添加外部列。FROM句子生成虛擬表VT1。
1、執(zhí)行笛卡爾積(CROSS JOIN)
笛卡爾積會(huì)把左右兩個(gè)表每一行所有可能的組合都列出來生成表VT1-J1,如果左表有m列,右表有n列,那么笛卡爾積之后生成的VT1-J1表將會(huì)有m×n列。
Step 1-J1這個(gè)步驟等價(jià)于執(zhí)行:
SELECT * from Customers C ?CROSS JOIN Orders O
執(zhí)行結(jié)果為:(共有4×7列)
C.customerid |
C.city |
O.orderid |
O.customerid |
FISSA |
Madrid |
1 |
FRNDO |
FISSA |
Madrid |
2 |
FRNDO |
FISSA |
Madrid |
3 |
KRLOS |
FISSA |
Madrid |
4 |
KRLOS |
FISSA |
Madrid |
5 |
KRLOS |
FISSA |
Madrid |
6 |
MRPHS |
FISSA |
Madrid |
7 |
NULL |
FRNDO |
Madrid |
1 |
FRNDO |
FRNDO |
Madrid |
2 |
FRNDO |
FRNDO |
Madrid |
3 |
KRLOS |
FRNDO |
Madrid |
4 |
KRLOS |
FRNDO |
Madrid |
5 |
KRLOS |
FRNDO |
Madrid |
6 |
MRPHS |
FRNDO |
Madrid |
7 |
NULL |
KRLOS |
Madrid |
1 |
FRNDO |
KRLOS |
Madrid |
2 |
FRNDO |
KRLOS |
Madrid |
3 |
KRLOS |
KRLOS |
Madrid |
4 |
KRLOS |
KRLOS |
Madrid |
5 |
KRLOS |
KRLOS |
Madrid |
6 |
MRPHS |
KRLOS |
Madrid |
7 |
NULL |
MRPHS |
Zion |
1 |
FRNDO |
MRPHS |
Zion |
2 |
FRNDO |
MRPHS |
Zion |
3 |
KRLOS |
MRPHS |
Zion |
4 |
KRLOS |
MRPHS |
Zion |
5 |
KRLOS |
MRPHS |
Zion |
6 |
MRPHS |
MRPHS |
Zion |
7 |
NULL |
2、應(yīng)用ON過濾,(JOIN 條件)
ON過濾條件是sql的三個(gè)過濾條件(ON,WHERE,HAVING)中最先執(zhí)行的,ON過濾條件應(yīng)用于前一步生成的虛擬表(VT1-J1),滿足ON過濾條件的行會(huì)被加入到虛擬表VT1-J2中。在應(yīng)用了ON 過濾之后,生成的VT1-J2表如下所示:
C.customerid |
C.city |
O.orderid |
O.customerid |
FRNDO |
Madrid |
1 |
FRNDO |
FRNDO |
Madrid |
2 |
FRNDO |
KRLOS |
Madrid |
3 |
KRLOS |
KRLOS |
Madrid |
4 |
KRLOS |
KRLOS |
Madrid |
5 |
KRLOS |
MRPHS |
Zion |
6 |
MRPHS |
本教程由尚硅谷教育大數(shù)據(jù)研究院出品,如需轉(zhuǎn)載請(qǐng)注明來源,歡迎大家關(guān)注尚硅谷公眾號(hào)(atguigu)了解更多。