如题:a表中数据为:
ID 内容
1   a
2   b
3   cb表中数据为
id  内容 ID
1    99   2其中b表中ID与a表中ID关联
然后我想显示出他们关联的数据
也就是
b.id b.内容 ID a.内容
1     99     2   b然后我还想显示出没有关联 但是符合要求的数据 比如a表内容为c的数据
b.id b.内容 ID a.内容
1     99     2   b
null  null   3   c 
查询语句要怎么写

解决方案 »

  1.   


    declare @a table(id int, 内容 varchar(5))
    insert into @a 
    select 1,'a' union all
    select 2,'b' union all
    select 3,'c'declare @b table(id int, 内容 varchar(5),id2 int)
    insert into @b values (1,'99',2)
    --第一个问题:
    select a.*,b.内容 from @b a left join @a b on a.id2=b.id 
    --结果
    id          内容    id2         内容
    ----------- ----- ----------- -----
    1           99    2           b(1 行受影响)--第二个问题
    select a.*,b.内容 from @b a left join @a b on a.id2=b.id 
    union all
    select a.*,b.内容 from @b a right join @a b on a.id2=b.id where b.内容='c'
    --结果
    id          内容    id2         内容
    ----------- ----- ----------- -----
    1           99    2           b
    NULL        NULL  NULL        c(2 行受影响)