在sql查询中获取递归数据

时间:2017-10-11 07:43:06

标签: php mysql laravel laravel-5 laravel-5.3

我有表用户,其中包含user_name和manager name。我想获取拥有manager =' test'。我想获得ramya作为经理和reportee的用户的用户名。 #39; s reportee

users table 
SNO user_name   manager
1    vani        Ramya
2    ramya       geetha
3    priya       ramya
4    mani        ramya
5    latha       vani
6.   hema        Anitha 

我想得到ramya和ramya的报告名称vani,priya和mani这个名字,并得到latha作为经理,他正在以ramya为经理。我想得到ramya,vani,priya,mani和latha

1 个答案:

答案 0 :(得分:1)

您可以使用以下查询:

select a.user_name from 
users a left join users b
on a.manager=b.user_name
where a.user_name='Ramya' or a.manager='ramya' or b.manager='Ramya'

输出:

| user_name |
|-----------|
|     latha |
|      vani |
|     priya |
|      mani |
|     ramya |

SQL小提琴:http://sqlfiddle.com/#!9/f57b06/10

P.S:我之前从未使用过Laravel,但在阅读了一些文档后,我认为查询可以这样写在那里

$users = DB::table('users as a')
            ->select('a.user_name')
            ->leftJoin('users as b', 'a.manager', '=', 'b.user_name')
            ->where('a.user_name','Ramya')
            ->orwhere('a.manager','Ramya')
            ->orwhere('b.manager','Ramya')
            ->get();