日期:2014-05-18  浏览次数:20555 次

简单的连接查詢
create Table A
(
id int,
name_cn varchar(50)
)
create table B
(
idB int,
name_en varchar(50)
)
insert A
select '1','河南'
union select '2','北京'
union select '3','南京'
union select '4','深圳'

insert B
select '1','wp'
union select '1','wp'
union select '3','zhangsan'
union select '5','lisi'
union select '6','wanger'
想查詢出 :
'1','河南','wp'
'2','北京',''
'3','南京','zhangsan'
'4','深圳',''

------解决方案--------------------
SQL code
create Table A
(
id int,
name_cn varchar(50)
)
create table B
(
idB int,
name_en varchar(50)
)
insert A
select '1','河南'
union select '2','北京'
union select '3','南京'
union select '4','深圳'

insert B
select '1','wp'
union select '1','wp'
union select '3','zhangsan'
union select '5','lisi'
union select '6','wanger'

select * from a
select * from b
select ''''+convert(varchar(8),A.id)+''''+','+''''+a.name_cn+''''+','+''''+isnull(B.name_en,'')+''''as bname_en 
from A left join B on A.id =B.idB 
/*
bname_en
'1','河南','wp'
'2','北京',''
'3','南京','zhangsan'
'4','深圳',''
*/

------解决方案--------------------
select A.id, a.name_cn,B.name_en from A left join B on A.id =B.idB
------解决方案--------------------
SQL code

select A.id,a.name_cn,isnull(B.name_en,'') as bname_en 
from A left join B on A.id =B.idB