我现在有三张表a,b,c  其中a.id=b.parent_id, b.id=c.parent_id,  有没有办法弄成像d表的样式呢?
a:
id1 字段1 字段2
1   aa     bb
b:
id parent_id 字段3
2   1         cc
3   1         dd
c:
id parent_id  字段4
 4    2             ee
 5    2             ff
 6    3             ggd:
id   字段1  字段2    id   Parent_id 字段3   id    parent_id  字段4
 1     aa     bb          2       1             cc      4      2             ee
null   null    null        null    null          null     5     2              ff
null   null    null        3       1             dd      6     3             gg方便于asp时读取,谢谢!

解决方案 »

  1.   

    我试着写了一下,因为机器没有装sql server,所以没有验证,仅供参考select case when b.id=(select min(id) from b where parent_id=b.id then a.id else null end ) as a_id,
           case when b.id=(select min(id) from b where parent_id=b.id then a.字段1 else null end ) as a_字段1,
           case when b.id=(select min(id) from b where parent_id=b.id then a.字段2 else null end ) a_字段2,
           case when c.id=(select min(id) from c where parent_id=c.id then b.id else null end ) as b_id,
           case when c.id=(select min(id) from c where parent_id=c.id then b.Parent_id else null end ) as b_Parent_id,
           case when c.id=(select min(id) from c where parent_id=c.id then b.字段3 else null end )b_字段3,
           c.id,
           c.parent_id,
           c.字段4
      from b
      left join a on b.parent_id = a.id
      right join c on b.id = c.parent_id