select 嵌套

来源:百度知道 编辑:UC知道 时间:2024/06/07 07:24:34
情况是这样的:
----------------------
表1(t1):
列1
p1
现有数据如下:
-------------
p1
1
2
3
------------
-----------------------------------
表2(t2)
列1 列2 列3
p1 q1 q3
2 4 0
2 5 1
----------------------------------

现在我要得到如下结果:

p1 q1(a)(where q2=0) q1(b)(where q2=1)
1 0 0
2 4 5
3 0 0

希望能看清内容,得到运行的结果,我用的是MYSQL 数据库,小弟把刚注册的20分全部送上,感激不尽!
不好意思版面太小不好编辑 表2的q3是q2
-----------------------------------
表2(t2)
列1 列2 列3
p1 q1 q2
2 4 0
2 5 1
----------------------------------

在SQL SERVER 2008中的SQL写法:
select c.p1,c.q1 as 'q1(a)(where q2=0)',d.q1 as 'q1(a)(where q2=1)'
from
(select t1.p1,a.q1 from t1
left join (select t1.p1,q1 from t1,t2 where t1.p1=t2.p1 and q2=0) as a on t1.p1=a.p1) as c
,
(select t1.p1,b.q1 from t1
left join (select t1.p1,q1 from t1,t2 where t1.p1=t2.p1 and q2=1) as b on t1.p1=b.p1) as d
where c.p1=d.p1
与楼主要求稍有不同,你要求出现"0"的地方结果是“空”(NULL),我认为这样更合理些。