如何使用oracle 11g中的SQL对象关系语句从两个表中提取数据

时间:2018-03-12 10:47:46

标签: sql oracle oracle11g

我正在尝试使用对象关系方法解决以下查询,但不知道什么是正确的方法。

查找每个分支的保存帐户数量,显示 号码和分店的地址。

我创建了两个表并插入了一些这样的数据:

- 这是分支表:

create type Branch_Address as object(
street varchar2(20),
city varchar2(20),
p_code varchar2(10))
not final
/

create type Branch_Phone as object(
phone varchar2(20))
not final;
/

create type branch_type as object(
bID varchar2(10),
bAddress Branch_Address,
bPhone Branch_Phone)
/

create table branch of branch_type(
primary key (bID))
/

insert into branch values(
'901',Branch_Address('Nic Street','Jordan','ABH887A'),Branch_Phone('0335454888'));
/
insert into branch values(
'906',Branch_Address('East End Garden','California','L181QP'),Branch_Phone('07455668711'));
/
insert into branch values(
'912',Branch_Address('Fredrick Street','London','LA112AS'),Branch_Phone('02841124478'));
/

insert into branch values(
'924',Branch_Address('West Street','Cambridge','CA8L871'),Branch_Phone('04511477885'));

- 这是帐户表

create type account_type as object(
accNum int,
accType varchar2(15),
balance number, 
bID ref branch_type,
inRate number,
limitOfFreeOD number,
openDate DATE)
/
create table account_table of account_type(
primary key (accNum))
/

insert into account_table
select account_type('1001','current','820.50',ref(b),'0.005','800','01-May-11')
from branch b
where b.bID = '901';
/

insert into account_table 
select account_type('1010','saving','2155',ref(b),'0.02','0','08-Mar-10')
from branch b
where b.BID = '906';
/
insert into account_table 
select account_type('1002','current','2600',ref(b),'0.005','1000','10-Apr-13')
from branch b
where b.BID = '912';
/
insert into account_table 
select account_type('1112','saving','24000',ref(b),'0','1700','16-Jun-16')
from branch b
where b.BID = '924';
/

分支( bID ,街道,城市,p_code,bPhone)

帐户( accNum ,accType,余额, bID ,inRate,limitOfFreeOD,openDate)

Bold是主键 斜体是外键(在对象关系中,如果我是对的,我们不使用Join)。

有任何帮助吗?感谢。

1 个答案:

答案 0 :(得分:0)

以下是您加入这些内容的方法:

select b.bid, 
    (select count(1) from account_table a 
      where a.bid.bid = b.bid
      and a.acctype='saving'
      ) as num_accounts,
    b.baddress.street, b.baddress.city, b.baddress.p_code 
from branch b;

这更令人困惑,因为branch_type.bIDvarchar2(10)account_type.bIDref branch_type。我会将account_type上的bID重命名为accBranch,以便更清楚它不存储ID,但是是对整个对象的引用。

我还没有对此查询进行过测试,但您也可以将其写为连接(下方)而不是子查询(上图)。它们各有用途。

select b.bid, count(1) as num_accounts,
    b.baddress.street, b.baddress.city, b.baddress.p_code 
from branch b
join account_table a
  on a.bid.bid = b.bid
  and a.acctype='saving'
group by b.bid, b.baddress.street, b.baddress.city, b.baddress.p_code;