簡體   English   中英

在 SQL 中創建具有父/子層次結構的表/表

[英]Create a table/tables with with parent/child hierarchy in SQL

我目前是一名自學成才的程序員,我知道並使用過 noSQL 數據庫。 現在我想更好地學習關系數據庫。 我正在為自己做一個項目,並試圖在這里加深我的知識,我有點困惑。 我的目標是創建一個具有子/父層次結構的簡單數據庫。 我想為人員創建一個數據庫,在其中我只能訪問身份證號(沒有姓名、年齡或其他)。 這個人可以有孩子或父母或兩者兼而有之。 如何建議我構建這個。 我想查詢該表,以便檢索某個人的所有孩子和父母。 我的第一個想法是用組合鍵(FK->Id_Number 和 Id_parent)構建一個只有 PK(Id_Number)和其他表的表,但我認為它不會像這樣工作? 我該怎么做? 你對此有什么想法嗎? 謝謝你!

為了幫助可視化(而不是識別號,讓我們使用名稱),我有這個 object,我應該如何存儲它?

 {
  human: "Joe",
  child: [
    {
      human: "Kevin",
      child: [
        {
          human: "Joaquin",
        },
        {
          human: "leticia",
        },
      ],
    },
    {
      human: "Mary",
      child: [
        {
          human: "Joaquin",
          child: [{ human: "levi" }],
        },
        {
          human: "leticia",
        },
      ],
    },
  ],
};

目標是了解所有家庭層次結構,例如誰是 kevin 的兒子、父母和可能的兄弟。

對實體之間的父關系建模的最簡單方法是為實體(圖中的節點)使用一個表,為關系(圖中節點之間的弧線)使用另一個表。

例如:

create table person (
  id int primary key not null,
  identification_number varchar(50) not null
);

create table parent_child_relationship (
  parent_id int not null references person (id),
  child_id int not null references person (id),
  primary key (parent_id, child_id),
);

您也可以使用單個表,但是將關系與實體分開可以讓您靈活地考慮擁有多個父母(自然、合法、收養等)的人,還可以考慮生活變化。

這就是我在 AWS redshift 中創建整合層次結構的方式。

這將為層次結構樹中的每個節點創建從上到下的層次結構

示例數據架構:

create table kpi_dashboard.employee (
 id int,
 name varchar (20),
 manager_id int
 );

插入數據

insert into schema_name.employee(id, name, manager_id)  values
(100, 'Carlos', null),
(101, 'John', 100),
(102, 'Jorge', 101),
(103, 'Kwaku', 101),
(110, 'Liu', 101),
(106, 'Mateo', 102),
(110, 'Nikki', 103),
(104, 'Paulo', 103),
(105, 'Richard', 103),
(120, 'Saanvi', 104),
(200, 'Shirley', 104),
(201, 'Sofía', 102),
(205, 'Zhang', 104);

生成的表:

id  name    manager_id
100 Carlos  
101 John    100
102 Jorge   101
103 Kwaku   101
110 Liu 101
106 Mateo   102
110 Nikki   103
104 Paulo   103
105 Richard 103
120 Saanvi  104

遞歸 SQL 以創建合並的層次結構路徑 -

with recursive Hierarchy (id,name,manager_id,Path)
AS
(
SELECT t.id,t.name,t.manager_id, CAST(t.name AS varchar(max))
FROM schema_name.employee AS t
LEFT JOIN schema_name.employee AS t1
ON t1.id = t.manager_id 
WHERE t1.id IS NULL
UNION ALL
SELECT t.id,t.name,t.manager_id, CAST(h.Path + '>' + t.name AS varchar(max))
FROM Hierarchy h
INNER JOIN schema_name.employee AS t
ON t.manager_id = h.id
)

SELECT id,name,Path
FROM Hierarchy

output:

id  name    path
100 Carlos  Carlos
101 John    Carlos>John
110 Liu Carlos>John>Liu
103 Kwaku   Carlos>John>Kwaku
102 Jorge   Carlos>John>Jorge
105 Richard Carlos>John>Kwaku>Richard
104 Paulo   Carlos>John>Kwaku>Paulo
110 Nikki   Carlos>John>Kwaku>Nikki
201 Sofía   Carlos>John>Jorge>Sofía
106 Mateo   Carlos>John>Jorge>Mateo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM