简体   繁体   English

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

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

First, I'll address concerns about duplicates:首先,我将解决有关重复的问题:

Here's a example of the problem I'm facing:这是我面临的问题的示例:

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
}

Ideally, I'd like to make it so that in 1 query, I can理想情况下,我想这样做,以便在 1 个查询中,我可以

  1. grab a document based on its id根据 id 抓取文档
  2. grab the relevant data from the correct child table从正确的子表中获取相关数据

Is this possible?这可能吗?

There are six ways (afaik) to model table inheritance in relational databases.在关系数据库中有六种方法(afaik)到 model 表 inheritance。 You chose the Permissive Class Table Inheritance option.您选择了Permissive Class Table Inheritance选项。

Now, you can use two left joins to retrieve information for child tables.现在,您可以使用两个左连接来检索子表的信息。 The resulting columns from the non-matching type will be null.非匹配类型的结果列将为 null。

For example:例如:

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

Result:结果:

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

See running example at DB Fiddle .请参阅DB Fiddle中的运行示例。 As you can see, column qux is null for type 2 and column baz is null for type 1.如您所见,对于类型 2,列qux是 null,对于类型 1,列 baz 是 null。

The sample structure for this example is shown below:此示例的示例结构如下所示:

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);

Note : Also please consider that to fully implement integrity you would need to include the type column in both foreign keys.注意:另外请考虑,要完全实现完整性,您需要在两个外键中包含type列。

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

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