我有数据表a,和b
乡建立视图,视图的关系是a.a=b.a
在两个表都有不止一条记录的情况下,如果符合a.a=b.a条件的记录没有,则视图自动把表b的第一条记录与表a形成试图。我在这里举例说明
a:
a a1 a2
1 a 1
2 b 2
3 c 3
b:
a b1 b2
1 x 1
2 y 2
我的视图(v_view1)包含了a.a , a.a1 , b.b1
我用select * from v_view1 where a=2 结果是:
a a1 b1
2 b y
(因为b中有a=2,a中也有a=2)
我用select * from v_view1 where a=3 结果是:
a a1 b1
3 c x
(因为b中有a=3,a中没有a=2)
select *from v_view1
a a1 b1
1 a x
2 b y
3 c x
---------------------------------------------------------------
select a.a, a.a1, isnull(b.b1, (select top 1 b1 from b)) from a left join b on a.a = b.a
---------------------------------------------------------------
先使用左连接处理,再对null值进行转换即可。
使用select a.a,a1,b1 from a left join b on a.a=b.a
会出现
a a1 b1
1 a x
2 b y
3 c null
然后对这个结果处理,也就是把b1的null值变成x
即是select a.a,a1,isnull(b1,x) from a left join b on a.a=b.a
这样结果就是
a a1 b1
1 a x
2 b y
3 c x
---------------------------------------------------------------
select a.a, a.a1, b.b1,b.b2,...b.b100 from a,b where a.a = b.a
union all
select a.a, a.a1,c.b1,c.b2,...c.b100 from a,(
select top 1 * from b ) as c
where not exists (select 1 from b where b.a=a.a)