簡體   English   中英

如何在mysql中進行多個自我聯接?

[英]How do I make multiple self joins in mysql?

我正在研究家譜數據庫。 簡單來說,一個稱為ancestors表由具有以下結構的記錄組成:

 name_id | name | mother_id | father_id
---------+------+-----------+-----------
       1 | John |         2 |         3
       2 | Mary |         4 |         5
       3 | Dave |         6 |         7

第一個查詢查找John的父母ID:例如John的父母ID為2和3

然后,再進行兩次查詢,找到父ID的父名稱:父ID 2的名稱為Mary,父ID 3的名稱為Dave。

使用三個查詢來發現:John的父母叫Mary和Dave。

可以通過單個查詢完成此操作,並且性能會有所提高嗎?

SELECT me.name,
       mother.name,
       father.name
  FROM ancestors me
  JOIN ancestors mother
    ON me.mother_id = mother.name_id
  JOIN ancestors father
    ON me.father_id = father.name_id
 WHERE ancestors.id = 1
;

是的,運行上述命令通常比運行三個單獨的查詢查詢要快。

像平常一樣聯接,但是每次都使用同一張表,為每個聯接賦予唯一的別名:

SELECT people.name_id, people.name, mothers.name_id, mothers.name, ...
FROM people
LEFT JOIN people AS mothers ON people.mother_id = mothers.name_id
LEFT JOIN people AS fathers ON people.father_id = fathers.name_id
etc...

看看圖noSQL數據庫。 它們非常適合您打算做的事情:

暫無
暫無

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

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