我正在尝试从表中自我加入信息,以显示层次结构(该表包含成员,其中包含子项及其父项)。表名是“成员”,四个重要的列是 id,full_name,father_id 和mother_id。列father_id和mother_id中的id匹配列'id'中的相应id。作为查询的结果,我希望有一个包含三列的表,列名为'Name','Father'和'Mother'
我搜索了谷歌,w3学校和堆栈溢出,最接近我正在寻找的是我在这里找到的一个主题,称为“自我加入的解释”,其中包含以下示例代码:
select
c1.Name , c2.Name As Boss
from
emp1 c1
inner join emp2 c2
on c1.Boss_id = c2.Id
我改变了查询如下(我甚至不敢包括第三列:')):
select
c1.full_name as Name, c2.full_name as Father
from
members1 c1
inner join members2 c2
on c1.father_id = c2.id
不幸的是,我收到一条错误消息,说明如下:1146 - 表'ppstb.members1'不存在
我猜测它与我如何模拟两张桌子有关。我接下来要尝试的是:
select
c1.full_name , c2.full_name as Father
from
members c1, members c2
inner join members c2
on c1.father_id = c2.id
但这也会出错:1066 - 不唯一的表/别名:'c2'我错过了哪一步?
答案 0 :(得分:0)
最后一个成员应该是c3而不是c2
select
c1.full_name , c3.full_name as Father
from
members c1, members c2
inner join members c3
on c1.father_id = c3.id
答案 1 :(得分:0)
我实际上使用左连接获得了代码。我不确定为什么内连接不起作用,但这解决了我的问题:
SELECT
members.full_name, b.full_name AS Father, c.full_name AS Mother
FROM
members
LEFT JOIN
members b ON (members.father_id = b.id)
LEFT JOIN
members c ON (members.mother_id = c.id)