mysql 查询递归自身,带有递归自联接的MySQL查询

I am trying to write a query with a recursive self join. My tables are something as below:

Table1

EMP_ID Name

1 Manger1

2 Manger2

3 Manger3

4 Employ1

5 Employ2

Table2

Par_EMP_ID EMP_ID

1 2

2 3

3 4

3 5

Here in above tables the Manager1, Manager2, ..., Employe2 are employees in a company where Manager1 is Head of Dept. Manager2 is reporting to Manager1, Manager3 is reporting to Manager2, this relation ship is maintained in table2 where Par_EMP_ID is EMP_ID of reportii and column EMP_ID is id of reporter. Now I want result as below:

Manager1 Manager2 Manager3 Employe1

Manager1 Manager2 Manager3 Employe2

解决方案

UPDATE:

According to your specs, here's the solution:

SELECT e.names member, d.name child

FROM MEMBERS d INNER JOIN

(SELECT a.id, GROUP_CONCAT(c.name) NAMES

FROM MEMBERS a

INNER JOIN RELATIONSHIP b ON a.id = b.MEM_ID

INNER JOIN MEMBERS c ON c.id = b.PAR_MEM_ID

GROUP BY a.id) e ON e.id = d.id

Result:

| MEMBER | CHILD |

|--------------------|--------------|

| Great Grand Father | Grand Father |

| Grand Father | Father |

| Father | Child1 |

| Father | Child2 |

Note:the results may depend on your sample data. And I updated also the SQLFiddle below so you might want to check that out.

Here's the SQLFiddle.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值