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

请教一个简单的连接查询的问题。谢谢
现有表1表2
table11,table2

table1:
id value1
1 100
2 200
3 700

table2:
id value2
1 98
3 99

我想得到的查询结果为
id value1 value2
1 100 98
2 200 0 (或者显示null也行)
3 700 99

sql该如何写?
而我实际得到结果中没有2号记录。


------解决方案--------------------
SQL code

select a.id,a.value1,b.value2 from table1 a left join table2 b on a.id=b.id

------解决方案--------------------
SQL code
select
  isnull(a.id,b.id) as id,isnull(a.value1,0) as value1,
  isnull(b.value2,0) as value2
from
  table1 a full join table2 b
on
  a.id=b.id

------解决方案--------------------
select tbl1.id,tbl1.value1,tbl2.value2 from tbl1 left join tbl2 on tbl1.id=tbl2.id

用左连接查询,你可能用了内连接
------解决方案--------------------
SQL code

if object_id('table1') is not null
   drop table table1
go
create table table1
(
 id int,
 value1 int
)
go
insert into table1
select 1,100 union all
select 2,200 union all
select 3,700
go
if object_id('table2') is not null
   drop table table2
go
create table table2
(
 id int,
 value2 int
)
go
insert into table2
select 1,98 union all
select 3,99
go
select a.id,a.value1,b.value2 from table1 a left join table2 b on a.id=b.id --显示null

select a.id,a.value1,value2=isnull(b.value2,0) from table1 a left join table2 b on a.id=b.id --显示0

/*
id          value1      value2
----------- ----------- -----------
1           100         98
2           200         0
3           700         99

(3 行受影响)

*/

------解决方案--------------------
SQL code
create table table1(id int,value1 int)
insert into table1 select 1,100
insert into table1 select 2,200
insert into table1 select 3,700
create table table2(id int,value2 int)
insert into table2 select 1,98
insert into table2 select 3,99
go
select a.id,a.value1,b.value2 from table1 a left join table2 b on a.id=b.id
/*
id          value1      value2
----------- ----------- -----------
1           100         98
2           200         NULL
3           700         99

(3 行受影响)

*/
go
drop table table1,table2

------解决方案--------------------
探讨
SQL code

select
isnull(a.id,b.id) as id,isnull(a.value1,0) as value1,
isnull(b.value2,0) as value2
from
table1 a full join table2 b
on
a.id=b.id