繁体   English   中英

如何在一个查询中查询父表和子表?

[英]How to query parent & child table in one query?

首先,我将解决有关重复的问题:

这是我面临的问题的示例:

table Document {
    id: Id
    name: string
    type: ??
}

table FooDoc {
   id: Id
   // Foreign key to Document
   docId: Id
   qux: string
}

table BarDoc {
   id: Id
   // Foreign key to document
   docId: Id
   baz: number
}

理想情况下,我想这样做,以便在 1 个查询中,我可以

  1. 根据 id 抓取文档
  2. 从正确的子表中获取相关数据

这可能吗?

在关系数据库中有六种方法(afaik)到 model 表 inheritance。 您选择了Permissive Class Table Inheritance选项。

现在,您可以使用两个左连接来检索子表的信息。 非匹配类型的结果列将为 null。

例如:

select d.*, f.qux, b.baz
from document d
left join foodoc f on f.id = d.id
left join bardoc b on b.id = d.id

结果:

 id  name  type  qux      baz  
 --- ----- ----- -------- ---- 
 20  baz1  2     null     1240 
 10  foo1  1     content  null 

请参阅DB Fiddle中的运行示例。 如您所见,对于类型 2,列qux是 null,对于类型 1,列 baz 是 null。

此示例的示例结构如下所示:

create table document (
  id int primary key not null, 
  name varchar(10), 
  type int not null check (type in (1, 2))
);

insert into document (id, name, type) values
  (10, 'foo1', 1),
  (20, 'baz1', 2);

create table foodoc (
  id int primary key not null references document(id),
  qux varchar(10)
);

insert into foodoc (id, qux) values (1, 'content');

create table bardoc (
  id int primary key not null references document(id),
  baz int
);

insert into bardoc (id, baz) values (2, 1240);

注意:另外请考虑,要完全实现完整性,您需要在两个外键中包含type列。

暂无
暂无

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

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