读书人

sql 筛选有关问题

发布时间: 2012-02-06 15:52:44 作者: rapoo

sql 筛选问题
create table t1(id1 int,name1 varchar(10))
create table t2(xuehao int,riqi int,chengji numeric(14,2))

insert into t1
select 1,'张三' union all
select 2,'李四' union all
select 3,'王五'

insert into t2
select 1,20100901,80 union all
select 2,20100801,79

问题:
select id1,name1,chengji
from t1 left join t2 on t1.id1=t2.xuehao
where riqi=20100902

这样一个左连接就没有数据了,我的目的是即使riqi没有id1,name1也应该有,在本例中想要也显示成
1,'张三' null
2,'李四' null
3,'王五' null

请高手给指点一下

[解决办法]

SQL code
select id1,name1,chengjifrom t1 Left join (select xuehao,chengji FROM t1 where riqi=20100902) b    on t1.id1=b.xuehao
[解决办法]
select a.*,case when riqi=20100902 then riqi end from t1 a left join t2 b on a.id1=b.xuehao

or

select id1,name1,chengji from t1 a Left join (select xuehao,chengji FROM t1 where riqi=20100902) b
on a.id1=b.xuehao

读书人网 >SQL Server

热点推荐