T-SQL筆記11_cross apply (inner join) 跟 outer apply(left outer join)

在一些關聯表的串接邏輯日常開發中
最常見的就是不同表之間join來join去

而 cross / outer apply 跟 join的功能有異曲同工之妙
差異在於不需要ON 表1.欄位A = 表2.欄位A 這種語法


cross apply 就相當於 inner join

outer apply 就相當於 left outer join

我們創建測試資料暫存表

SQL:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
USE [tempdb] 
GO
 
IF EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[Employee]') AND type IN (N'U')) 
BEGIN 
   DROP TABLE [Employee] 
END 
GO 

IF EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[Department]') AND type IN (N'U')) 
BEGIN 
   DROP TABLE [Department] 
END 

CREATE TABLE [Department]( 
   [DepartmentID] [int] NOT NULL PRIMARY KEY, 
   [Name] VARCHAR(250) NOT NULL, 
) ON [PRIMARY] 

INSERT [Department] ([DepartmentID], [Name])  
VALUES (1, N'Engineering') 
INSERT [Department] ([DepartmentID], [Name])  
VALUES (2, N'Administration') 
INSERT [Department] ([DepartmentID], [Name])  
VALUES (3, N'Sales') 
INSERT [Department] ([DepartmentID], [Name])  
VALUES (4, N'Marketing') 
INSERT [Department] ([DepartmentID], [Name])  
VALUES (5, N'Finance') 
GO 

CREATE TABLE [Employee]( 
   [EmployeeID] [int] NOT NULL PRIMARY KEY, 
   [FirstName] VARCHAR(250) NOT NULL, 
   [LastName] VARCHAR(250) NOT NULL, 
   [DepartmentID] [int] NOT NULL REFERENCES [Department](DepartmentID), 
) ON [PRIMARY] 
GO
 
INSERT [Employee] ([EmployeeID], [FirstName], [LastName], [DepartmentID]) 
VALUES (1, N'Orlando', N'Gee', 1 ) 
INSERT [Employee] ([EmployeeID], [FirstName], [LastName], [DepartmentID]) 
VALUES (2, N'Keith', N'Harris', 2 ) 
INSERT [Employee] ([EmployeeID], [FirstName], [LastName], [DepartmentID]) 
VALUES (3, N'Donna', N'Carreras', 3 ) 
INSERT [Employee] ([EmployeeID], [FirstName], [LastName], [DepartmentID]) 
VALUES (4, N'Janet', N'Gates', 3 ) 


select * from Department
select * from Employee


這是兩表的資料(部門及員工)



觀察一下測試語法比較

cross apply 就相當於 inner join

SQL

1
2
3
4
5
6
7
8
9
select * from Department D
inner join Employee E
ON D.DepartmentID = E.DepartmentID

select * from Department D
cross apply (
	select * from Employee E
	where E.DepartmentID = D.DepartmentID
) A



outer apply 就相當於 left outer join

SQL

1
2
3
4
5
6
7
8
9
select * from Department D 
left outer join Employee E 
ON D.DepartmentID = E.DepartmentID

select * from Department D
outer apply (
	select * from Employee E
	where E.DepartmentID = D.DepartmentID
) A













Ref:

合併查詢結果

SQL Server CROSS APPLY and OUTER APPLY


14. CROSS APPLY 與 OUTER APPLY


SQL OUTER APPLY CROSS APPLY 用法


留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題