gpt4 book ai didi

mysql - SQL:如何加入分层表关系

转载 作者:行者123 更新时间:2023-11-28 23:15:12 25 4
gpt4 key购买 nike

我有 3 个表,分别是 DepartmentOfficeDivision

假设流程是:Department has Offices has Division

但有些情况下 Divisions 直接向 Departments 报告

示例数据

Department   Office                Division
[id][name] [dept_id][id][name] [dept_id][off_id][id][name]
[ 1][A ] [ 1 ][ 1][D ] [ 1 ][ 2 ][ 1][G ]
[ 2][B ] [ 1 ][ 2][E ] [ 3 ][ NULL ][ 2][H ]
[ 3][C ] [ 3 ][ 3][F ] [ 3 ][ 3 ][ 3][I ]

显示所有部门的期望输出:

OUTPUT
[AS dept_name][AS off_name][AS div_name]
[ A ][ E ][ G ]
[ C ][ NULL ][ H ]
[ C ][ F ][ I ]

我当前的查询是:

    SELECT * FROM `Division` A 
RIGHT JOIN `Office` B ON A.`off_id` = B.`id`
RIGHT JOIN `Department` C ON A.`dept_id` = C.`id`;

我的查询是错误的,所以我正在寻找一种方法来连接这 3 个表以获得所需的输出

最佳答案

如果要显示所有部门,需要使用LEFT JOIN

SELECT
Department.`name` AS dept_name,
Office.`name` AS off_name,
Division.`name` AS div_name
FROM
Division
LEFT JOIN Office ON Division.off_id = Office.id
LEFT JOIN Department ON Division`.dept_id = Department.id;

关于mysql - SQL:如何加入分层表关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44197184/

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