我有3张桌子:
CREATE TABLE B (
id INTEGER PRIMARY KEY,
personName VARCHAR2(200)
);
CREATE TABLE C (
id INTEGER PRIMARY KEY,
companyName VARCHAR2(200)
);
CREATE TABLE A (
id INTEGER PRIMARY KEY,
id_b INTEGER REFERENCES B(id),
id_c INTEGER REFERENCES C(id),
CHECK ( id_b IS NULL OR id_c IS NULL )
);
但是表A一次只指向一个表:如果idB有值,则idC为null。
我现在正在尝试执行单个查询,其中我选择所有行和每行:要么是人行(id,id_B,personName),要么是公司行(id,id_B,companyName)。< / p>
有没有办法在不使用存储过程的情况下执行此操作?
答案 0 :(得分:1)
select
a.id,
coalesce(b.id, c.id),
coalesce(b.person_name, c.company_name)
from
A a,
B b,
C c
where
a.id_b = b.id (+) and
a.id_c = c.id (+)
P.S。也许你应该考虑改变你的检查约束,如nvl2(id_b, 1, 0) + nvl2(id_c, 1, 0) = 1
答案 1 :(得分:0)
试试这个:
select id,id_b,personName from A join B on A.id_b = B.id
union all
select id,id_c,companyName from A join C on A.id_c = C.id