SQL Server联合查询

JOIN: 如果表中有至少一个匹配,则返回行
LEFT JOIN: 即使右表中没有匹配,也从左表返回所有的行
RIGHT JOIN: 即使左表中没有匹配,也从右表返回所有的行
FULL JOIN: 只要其中一个表中存在匹配,就返回行

一、inner join
select city.name as 城市, area.name as 地区 from area
inner join city
on city.code = area.cityid
或者
select c.name,a.name from area as a
inner join city as c
on c.code=a.cityid

二、left join
select city.name as 城市,area.name as 地区 from area 
left join city
on city.code = area.cityid
或者
select c.name as 城市,a.name as 地区 from area as a
left join city as c
on c.code = a.cityid

三、right join
select city.name as 城市,area.name as 地区 from area 
right join city
on city.code = area.cityid
或者
select c.name as 城市,a.name as 地区 from area as a
right join city as c
on c.code = a.cityid

四、full join
select city.name,area.name from area
full join city
on city.code = area.cityid
--或者
select c.name,a.name from area as a
full join city as c
on c.code = a.cityid

 

表结构

City表

[sql] view plain copy print ?
  1. CREATE TABLE [dbo].[city](  
  2.  [id] [intNOT NULL,  
  3.  [code] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL,  
  4.  [name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,  
  5.  [provinceId] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL  
  6. ON [PRIMARY]  

Area表

[sql] view plain copy print ?
  1. CREATE TABLE [dbo].[area](  
  2.     [id] [intNOT NULL,  
  3.     [code] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,  
  4.     [name] [nvarchar](60) COLLATE Chinese_PRC_CI_AS NULL,  
  5.     [cityId] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL  
  6. ON [PRIMARY]  

你可能感兴趣的:(JOIN,sql,sql,server,null,table)