如何使用SQL实现查询,帮忙啊!(200分)(200分)

  • 主题发起人 主题发起人 bluestar_sz
  • 开始时间 开始时间
B

bluestar_sz

Unregistered / Unconfirmed
GUEST, unregistred user!
我有三个表,分别为A,B,C,其中A为主表,B和C都为子表,
分别如下:
C:
ID NAME
1 XXX
2 YYY
B:
ID NAME
1 EEE
2 AAA
A:
NAMEID1 NAMEID2 NAME3 NAME4 RYID (当用B表时为0,当用C表时为1)
1 2 0
1 1
1 2 1
我现在想实现如下查询:
NAME1 NAME2 NAME3 NAME4
EEE AAA
XXX
XXX YYY
不知道如何使用SQL实现,希望各位帮忙。200相送。
 
这个查询没有办法直接使用sql实现,必须借助于条件的判断使用动态生成的sql才能实现。
 
select case when ryid=0 then (select b.name from b where b.id=a.nameid1)
when ryid=1 then (select c.name form c where c.id=a.nameid2)
end,
case when ryid=0 then (select b.name from b where b.id=a.nameid1)
when ryid=1 then (select c.name form c where c.id=a.nameid2)
end,
.......
from a
 
select "name1"= case
when ryid=0 then (select b.name from b where b.id=a.nameid1)
when ryid=1 then (select c.name form c where c.id=a.nameid1)
end,

"Name2"=
case
when ryid=0 then (select b.name from b where b.id=a.nameid2)
when ryid=1 then (select c.name form c where c.id=a.nameid2)
end
from a
 
可以的
SELECT b1.name AS name1,b2.name AS name2 FROM a a1,b b1,b b2
WHERE a1.nameid1=b1.id AND a1.nameid2=b2.id AND a1.ryid='0' UNION
SELECT c1.name AS name1,c2.name AS name2 FROM a a2,c c1,c c2
WHERE a2.nameid1=c1.id AND a2.nameid2=c2.id AND a2.ryid='1'
 
TO WANGJIANKANG_71:
你的方法不全,如我举例的查询表的第二行就没有,你考虑一下null的情况
 
加上ISNULL不就可以拉
 
select case when ryid=0 then (select b.name from b where b.id=a.nameid1)
when ryid=1 then (select c.name form c where c.id=a.nameid2)
end,
case when ryid=0 then (select b.name from b where b.id=a.nameid1)
when ryid=1 then (select c.name form c where c.id=a.nameid2)
end,
.......
from a


给分!
 
我用的是Interbase,以上的SQL语句不行,不能用case
 
建议你在B,C两个表分别再加一条记录:
C:
ID NAME
1 XXX
2 YYY
3 null
ID NAME
1 EEE
2 AAA
3 null
A:表的存取为:
A:
NAMEID1 NAMEID2 NAME3 NAME4 RYID (当用B表时为0,当用C表时为1)
1 2 0
1 3 1
1 2 1

 
告诉你的是方法,为什么只注重些形式的东西呢,你是问问题还是抬杠,给你一个SOLUTION
中最关键的IDEA已经足够了,不是吗?迂腐的人!
用FULL OUTER JION
SELECT b1.name AS name1,b2.name AS name2 FROM a a1 FULL OUTER JOIN b b1 ON
a1.nameid1=b1.id FULL OUTER JOIN b b2 ON a1.nameid2=b2.id where a1.ryid='0'
UNION
SELECT c1.name AS name1,c2.name AS name2 FROM a a2 FULL OUTER JOIN c c1 ON
a2.nameid1=c1.id FULL OUTER JOIN c c2 ON a2.nameid2=c2.id WHERE a2.ryid='1'
 
to wangjiankang_71:
我发现你是不是有问题?我需要的是idea,如果你不回答,没人会觉得你没有嘴巴的。你太
多嘴了,什么叫形式,什么叫idea,我不用你来多说。告诉你问题我已经解决了,没有用你
的idea,你别在我面前自以为是的。大白痴。
 
汝子不可教呀
 
to wangjiankang_71:
大g,你也太自以为是了吧。算了吧,对于你的自以为是小弟甘拜下风。
 
后退
顶部