我的桌子
GROUPS
----------
id | groupName
4 Personal
5 Friends
6 University
Records
----------
id | groupId | name
1 4 Majid
2 4 Jawad
3 5 Zain
4 5 Mohsin
5 6 Ismail
7 6 Zubair
groups_connected
--------------------
id | parent_id | child_id
1 4 5
2 5 6
这是我的表结构,我希望在php中显示每个组联系人及其父联系人。 例如。当查看组5朋友时,我想获得groupId 5及其父组记录的记录。 当有人想要观看第6组大学时。结果应该是大学组,朋友组和个人组 如果该组未与任何组关联,则仅显示该组记录。
答案 0 :(得分:0)
您需要使用不同的别名加入GROUPS
和Records
两次。
试试这个:
SELECT GC.id,R1.name as parent,G1.groupName as ParentGroup,R2.name as child,G2.groupName as ChildGroup
FROM groups_connected GC FULL OUTER JOIN
Records R1 ON GC.parent_id = R1.id FULL OUTER JOIN
GROUPS G1 ON R1.groupId = G1.id FULL OUTER JOIN
Records R2 ON GC.child_id = R2.id FULL OUTER JOIN
GROUPS G2 ON R2.groupId = G2.id
WHERE G1.id = 5 OR G2.id = 5