1. 程式人生 > 其它 >自聯結和子查詢的區別

自聯結和子查詢的區別

技術標籤:SQL

通過以下例項,來驗證自聯結和子查詢的區別

題目:目前有兩張表,cust_info是客戶表,order_list是訂單表,兩張表都有同樣的欄位名cust_id
要求查詢客戶趙一的所有訂單資訊,要求結果如下:
在這裡插入圖片描述

解題思路:
1.首先篩選出客戶趙一的對應訂單id
2.再根據訂單id找到對應的訂單資訊

解法一:子查詢:

select *
from order_list 
where cust_id=(
               select cust_id 
			   from cust_info 
			   where cust_name='趙一'
							 )
;

解法二:自聯結1

select o.*
from order_list o INNER JOIN cust_info c
on c.cust_id=o.cust_id
where c.cust_name='趙一'

解法三:自聯結2

select o.*
from order_list o
,cust_info c
where c.cust_id=o.cust_id
and c.cust_name='趙一';

總結:
1.自聯結是子查詢的簡化,自聯結的程式碼行數更少
2.同時自聯結的執行速度更快