日期:2014-05-19  浏览次数:20696 次

一个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了,呵呵

學習學習