读书人

求SQL语句:两表查询,该如何处理

发布时间: 2012-03-14 12:01:12 作者: rapoo

求SQL语句:两表查询
表1
字段1 字段2
1 a
2 a
3 a
1 b
2 b
3 b


表2
字段
1
2
3
4
5

以表1的字段2为查询条件,如结果为:
字段1 字段2
1 a
2 a
3 a
4
5


求SQL语句

[解决办法]

SQL code
--> 测试数据: @表1declare @表1 table (字段1 int,字段2 varchar(1))insert into @表1select 1,'a' union allselect 2,'a' union allselect 3,'a' union allselect 1,'b' union allselect 2,'b' union allselect 3,'b'--> 测试数据: @表2declare @表2 table (字段 int)insert into @表2select 1 union allselect 2 union allselect 3 union allselect 4 union allselect 5select a.*,b.字段2 from @表2 a left join @表1 b on a.字段=b.字段1 and b.字段2='a'/*字段          字段2----------- ----1           a2           a3           a4           NULL5           NULL*/ 

读书人网 >SQL Server

热点推荐