繁体   English   中英

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

[英]How to extract data from two tables using SQL object relational statement in oracle 11g

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

查找每个分支机构的储蓄帐户数量,并显示该数量和分支机构的地址。

我创建了两个表,并插入一些数据,如下所示:

-这是分支表:

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,balance, bID ,inRate,limitOfFreeOD,openDate)

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

有什么帮助吗? 谢谢。

您可以通过以下方式加入这些人:

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上的accBranch重命名为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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM