1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | create table Customers (Cust_Id int , Cust_Name varchar (10)) insert Customers values (1, 'Craig' ) insert Customers values (2, 'John Doe' ) insert Customers values (3, 'Jane Doe' ) create table Sales (Cust_Id int , Item varchar (10)) insert Sales values (2, 'Camera' ) insert Sales values (3, 'Computer' ) insert Sales values (3, 'Monitor' ) insert Sales values (4, 'Printer' ) |
Inner joins(内连接)Inner join是最常见的连接类型。一个inner join只是简单的找到两行,然后根据连接的谓词放在一起。例如,下面的查询使用这样的连接谓词“S.Cust_Id = C.Cust_Id”来找在Sales和Customer表中具有相同Cust_Id的行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | select * from Sales S inner join Customers C on S.Cust_Id = C.Cust_Id Cust_Id Item Cust_Id Cust_Name ----------- ---------- ----------- ---------- 2 Camera 2 John Doe 3 Computer 3 Jane Doe 3 Monitor 3 Jane Doe |
注意:Cust_Id 3 买了两件item,所以该Customer会在结果中出现两次.Cust_Id 1 没有购买任何东西,所以没在结果中出现。我们卖了一个‘Printer’ 给 Cust_Id 4。但这边没有这个客户,所以在结果里面也看不到该客户。Inner Join是中表的位置是可以交换的。也就是说‘A inner join B ‘ 等价于’B inner join A’。Outer joins(外连接)假设我们想要看到所有的sales的列表,即使是那些没有匹配的客户。我们可以通过外连接来实现。外连接会保留其中一个或者两个输入表里的所有行,即使我们通过join谓词找不到匹配的行。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | select * from Sales S left outer join Customers C on S.Cust_Id = C.Cust_Id Cust_Id Item Cust_Id Cust_Name ----------- ---------- ----------- ---------- 2 Camera 2 John Doe 3 Computer 3 Jane Doe 3 Monitor 3 Jane Doe 4 Printer NULL NULL |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | select * from Sales S full outer join Customers C on S.Cust_Id = C.Cust_Id Cust_Id Item Cust_Id Cust_Name ----------- ---------- ----------- ---------- 2 Camera 2 John Doe 3 Computer 3 Jane Doe 3 Monitor 3 Jane Doe 4 Printer NULL NULL NULL NULL 1 Craig |
1 2 3 4 5 6 | Join 保留… ------------------------------------------- A left outer join B all A rows A right outer join B all B rows A full outer join B all A and B rows |