读书人

一个SQL联合查询的有关问题

发布时间: 2012-01-19 00:22:27 作者: rapoo

一个SQL联合查询的问题
表a字段
id pid des
1 1 f
2 3 x
2 4 c


表b字段
pid des
1 a
2 b
3 c
4 c

我需要得到两张表的联合查询结果如下
表c

id pid des
1 1 f
1 2 null
1 3 null
1 4 null
2 1 null
2 2 null
2 3 x
2 4 c


[解决办法]
select a1.*,a2.des
from (
select id,pid
from (
select distinct id from a
) as x cross join (
select distinct pid from b
) as y
) as a1 left join a a2
where a1.id=a2.id
and a1.pid=a2.pid

[解决办法]
上倒第二行where要改成on

最後再加上order by a1.id就OK了,呵呵

读书人网 >SQL Server

热点推荐