关于外表关联的查询语句问题?
现在有两张表,其中有一个字段是相同的。存在这样一个问题,从这两张表中取数据,其中A表中的这个字段的值在B表中,也许会找不到。但又想保证这两张表相关联后,A表有多少条记录,查询后也有相同的记录。该如何解决?
例:A表中有id,name,phone三个字段.在B表中有system,gzdm,phone,azdz四个字段。
A表的数据如下:(1,yifei,5215553)、(2,cctv,4214243)、(3,cdqy,4324232)
B表的数据如下:(01,20,5215553,长沙)、(02,21,4214243,娄底)、(03,22,85739323,广东)、(04,23,6738383,海南)
现在我希望得到这样的数据:id,name,phone,system,gzdm 以A表为主表,即要得到A表中所有的记录.例:(1,yifei,5215553,01,0)、(2,cctv,4214243,01,20)、(3,cdqy,4324232,0,0)
即如果phone字段在两张表中不匹配,则在B表中的字段用默认值。
问题点数:100、回复次数:15Top
1 楼KingSunSha(弱水三千)回复于 2002-04-29 21:54:58 得分 70
select id, name, a.phone,
nvl(b.system,'0') system, nvl(b.gzdm,'0') gzdm
from a, b
where a.phone = b.phone((+);Top
2 楼jlandzpa(jlandzpa)回复于 2002-04-29 22:01:26 得分 5
agreeTop
3 楼hrb_qiuyb(晨钟暮鼓)回复于 2002-04-30 07:54:20 得分 10
其实就是外连接的问题,在oracle中使用"+"
如a.col1=b.col1(+)这样的意思为当b中没有与a相同值的记录时补空值,这时你可以用nvl()为空值置其它一些值。Top
4 楼xinpingf(白开心)回复于 2002-04-30 09:20:32 得分 5
弱水兄,多写了半个括号Top
5 楼mycode(不写代码)回复于 2002-04-30 10:55:04 得分 0
对,就是外连接,在右边使用"+"就可以了.Top
6 楼topson_fj(liang)回复于 2002-04-30 11:02:29 得分 0
外连接问题,多看看书吧!Top
7 楼mashansj(风影)回复于 2002-04-30 11:55:54 得分 10
select id, name, a.phone,
nvl(b.system,'0') system, nvl(b.gzdm,'0') gzdm
from a, b
where a.phone = b.phone(+);
Top
8 楼KingSunSha(弱水三千)回复于 2002-04-30 22:20:06 得分 0
xinpingf(白开心):白兄好眼力!随手写的,大意了,不好意思Top
9 楼teng(blackeyes)回复于 2002-05-05 09:07:05 得分 0
关注Top
10 楼xiangdie(湘蝶)回复于 2002-05-16 10:06:37 得分 0
如果A表结构为:a_id,a_name,b_id,a_type;
B表结构为:b_id,b_name,....
我要查出所有A 表中的内容转为:a_name,b_name,a_type.而A表的某条记录中b_id可能为空,这时也要查出这条记录,此时b_name可以用空值代替,怎么查?Top
11 楼KingSunSha(弱水三千)回复于 2002-05-16 12:15:15 得分 0
select a_name, b_name, a_type
from a, b
where a.b_id = b.b_id
union all
select a_name, null, a_type
from a
where a.b_id is null;Top
12 楼KingSunSha(弱水三千)回复于 2002-05-16 13:00:14 得分 0
另外,如果是oracle 8i或以上版本,可以这么写
select a_name,
(select b_name from b where b.b_id=a.b_id) b_name,
a_type
from a
where a.b_id = b.b_id
Top
13 楼KingSunSha(弱水三千)回复于 2002-05-16 13:01:53 得分 0
上面忘了删掉最后一句,应该是:
select a_name,
(select b_name from b where b.b_id=a.b_id) b_name,
a_type
from a;
Top
14 楼xiangdie(湘蝶)回复于 2002-05-16 14:17:53 得分 0
I see, 谢谢KingSunSha(弱水三千)Top
15 楼KingSunSha(弱水三千)回复于 2002-05-16 15:18:05 得分 0
啊,原来你不是贴主啊,我都搞糊涂了Top
16 楼cdqy(触电)回复于 2002-05-21 09:53:38 得分 0
谢谢,我已搞定了.我用的数据库是informix.解决方法:
加outer就行.
select id, name, a.phone from a,outer(b) where a.phone = b.phone;
Top




