簡體   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