请教一条SQL的写法

requeleme 2008-09-25 08:36:16
假设要储存公司员工的电话号码,但可能有员工既有公司电话,又有家庭电话,也可能有员工只有公司电话或家庭电话.
我设计了三张表来存放上述信息.
1 clerk_info 职工基本信息
create table clerk_info
(
id number,
name varchar2(20),
primary key id
}
2 hometel 家庭电话表
create table hometel
(
id number,
tel varchar2(8),
primary key id,
foreign key (id) reference clerk_info(id)
)

3 companytel 公司电话表
create table companytel
(
id number,
tel varchar2(8),
primary key id,
foreign key (id) reference clerk_info(id)
)

根据上面的表,我要查询出如下的结果,应该怎么写SQL文
id hometel company
1 12345678
2 23456789 34567890
3 45678901

...全文
99 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
daifeng130 2008-09-26
  • 打赏
  • 举报
回复
没有必要搞这么多表,有时候为了速度和方便,浪费点空间是值得的。
requeleme 2008-09-25
  • 打赏
  • 举报
回复
为了不浪费空间,因为如果合成一张表的话,一个人如果只有家庭电话,没有公司电话,这条记录的一个字段就为空了,这样就浪费了空间.
tangshd 2008-09-25
  • 打赏
  • 举报
回复
既然是这样..为何不放到一个表里?
requeleme 2008-09-25
  • 打赏
  • 举报
回复
上面的似乎写错了?
应该是
select clerk_info.id as id,hometel.tel as hometel,companytel.tel as company
from clerk_info
left join hometel on clerk_info.id=hometel.id
left join companytel on hometel.id=companytel.id

两个都是左外连接,一个人可能多个电话号码
lbs_super 2008-09-25
  • 打赏
  • 举报
回复
使用左连接和内连接就可以搞定
具体SQL语句如下:
select clerk_info.id as id,hometel.tel as hometel,companytel.tel as company
from clerk_info
left join hometel on clerk_info.id=hometel.id
inner join companytel on hometel.id=companytel.id

其中hometel.id和companytel.id指的是与职工表相关联的外键


cyc_cheng 2008-09-25
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 requeleme 的回复:]
上面的似乎写错了?
应该是
select clerk_info.id as id,hometel.tel as hometel,companytel.tel as company
from clerk_info
left join hometel on clerk_info.id=hometel.id
left join companytel on hometel.id=companytel.id

两个都是左外连接,一个人可能多个电话号码
[/Quote]

这个还不对,companytel表和hometel没有直接的关联,他们都是与clerk_info有关系,写成hometel.id=companytel.id 不行吧
cyc_cheng 2008-09-25
  • 打赏
  • 举报
回复

select ci.id as id,hm.tel as hometel,cp.tel as companytel
from clerk_info ci
left join hometel hm on hm.id=ci.id
left join companytel cp on cp.id=ci.id

结果:
id hometel companytel
1 12345678
2 23456789 34567890
3 45678901

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧