在 PL/SQL 中完成的问题的解决方案在 SQL 中会是什么样子?
我已经使用 PL/SQL 和 SQL 编写了一个问题解决方案,我不禁认为它可以 100% 用 SQL 完成,但我正在努力开始。
这是两个表的结构(如果有帮助,创建它们的脚本位于问题的末尾)
表 t1(主键是显示的两列)
ID TYPE
1 A
1 B
1 C
2 A
2 B
3 B
类型列是表 T2 的外键,其中包含以下内容数据:
表 t2 (主键是类型)
Type Desc
A xx
B xx
C xx
因此,给定 T1 中的数据,我需要的结果将是:
对于 ID 1,因为它具有外键表中的所有类型,对于 ID 2,我将返回文字“全部”,
因为它有两种类型我想返回“A & B”(注意分隔符)
最后对于 ID 3,因为它有一种类型我只想返回“B”
正如这里所承诺的是创建所有对象的脚本提及。
create table t2(type varchar2(1),
description varchar2(100)
)
/
insert into t2
values ('A', 'xx')
/
insert into t2
values ('B', 'xx')
/
insert into t2
values ('C', 'xx')
/
alter table t2 add constraint t2_pk primary key (type)
/
create table t1 (id number(10),
type varchar2(1)
)
/
alter table t1 add constraint t1_pk primary key(id, type)
/
alter table t1 add constraint t1_fk foreign key (type)
references t2(type)
/
insert into t1
values (1, 'A')
/
insert into t1
values (1, 'B')
/
insert into t1
values (1, 'C')
/
insert into t1
values (2, 'A')
/
insert into t1
values (2, 'B')
/
insert into t1
values (3, 'B')
/
I've written a solution to problem using PL/SQL and SQL and I can't help thinking that it could be done 100% in SQL but am I am struggling to get started.
Here is the structure of the two tables (If it helps, the scripts to create them are at the end of the question)
Table t1 (primary key is both columns displayed)
ID TYPE
1 A
1 B
1 C
2 A
2 B
3 B
The Type column is a Foreign Key to table T2 which contains the following data:
Table t2 (primary key is Type)
Type Desc
A xx
B xx
C xx
So given the the data in T1 the result I need will be:
For ID 1 because it has all the types in the foreign key table I would return the literal "All"
For ID 2 because it has two types I would like to return "A & B" (note the separator)
And finally for ID 3 because it has one type I would like to return just "B"
As promised here are the scripts to create all the objects mentioned.
create table t2(type varchar2(1),
description varchar2(100)
)
/
insert into t2
values ('A', 'xx')
/
insert into t2
values ('B', 'xx')
/
insert into t2
values ('C', 'xx')
/
alter table t2 add constraint t2_pk primary key (type)
/
create table t1 (id number(10),
type varchar2(1)
)
/
alter table t1 add constraint t1_pk primary key(id, type)
/
alter table t1 add constraint t1_fk foreign key (type)
references t2(type)
/
insert into t1
values (1, 'A')
/
insert into t1
values (1, 'B')
/
insert into t1
values (1, 'C')
/
insert into t1
values (2, 'A')
/
insert into t1
values (2, 'B')
/
insert into t1
values (3, 'B')
/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样的东西应该可以满足您的需求:
如果我可以发布您的对象/数据创建脚本,我会给您的问题+10!
Something like this should get you what you are looking for:
I would give your question +10 if I could for posting your object / data creation script!