gpt4 book ai didi

mysql - 如何使用 MySQL 进行多重连接?

转载 作者:行者123 更新时间:2023-11-29 06:52:07 26 4
gpt4 key购买 nike

假设我有三个处于直接 OneToMany 关系中的表。

grandparent TABLE
-----------------
id PK AI

parent TABLE
-----------------
id PK AI
grandparent_id FK ManyToOne NOT NULL

child TABLE
-----------------
id PK AI
parent_id FK ManyToOne NOT NULL

当我想在选择 child 的同时选择 parent 和祖 parent 时,以下两个查询哪个正确?

SELECT * FROM child AS c
INNER JOIN (parent AS p INNER JOIN grandparent AS g ON p.grandparent_id = g.id)
ON c.parent_id = p.id

SELECT * FROM child AS c
INNER JOIN parent AS p ON c.parent_id = p.id
INNER JOIN grandparent AS g ON p.grandparent_id = g.id

它们的内部和外部相同吗?

最佳答案

我会离开连接两次,从祖 parent 到 parent ,然后到 child 。其背后的动机是,并非所有祖先都有 child ,但您可能仍希望将他们包含在报告中。

SELECT
t1.ID AS grandparent_id
CASE WHEN t2.ID IS NOT NULL
THEN CAST(t2.ID AS VARCHAR) ELSE 'NA' END AS parent_id,
CASE WHEN t3.ID IS NOT NULL
THEN CAST(t3.ID AS VARCHAR) ELSE 'NA' END AS child_id
FROM grandparent t1
LEFT JOIN parent t2
ON t1.ID = t2.grandparent_id
LEFT JOIN child t3
ON t2.ID = t3.parent_id
ORDER BY
t1.ID, t2.ID, t3.ID;

关于mysql - 如何使用 MySQL 进行多重连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47047812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com