带有左联接的Laravel选择查询

时间:2018-08-27 06:49:28

标签: mysql laravel select

表格-tbl_user_details

UserId  | Username
------------------
1       |  jijo
2       |  libin

表-tbl_user_followups

FollowupId  |  UserId  |  Status
---------------------------------
1           |  1       |  Negative
2           |  1       |  Neutral
3           |  1       |  Positive

我的控制器是

$result= DB::table('tbl_user_details')
                        ->leftjoin('tbl_user_followups','tbl_user_details.UserId','=','tbl_user_followups.UserId')
                        ->select('tbl_user_details.*','tbl_user_followups.*')

                        ->orderBy('tbl_user_followups.FollowupId','DESC')
                        ->groupBy('tbl_user_details.UserId')
                        ->get();

我想获得如下输出

UserId  | Username | FollowupId  |  Status
----------------------------------------
1       |  jijo    |    3        |  Positive
2       |  libin

任何人都可以在我的控制器中提出修改建议吗?

1 个答案:

答案 0 :(得分:2)

不确定我是否理解正确的问题:您想要最后一个“关注”的用户列表吗?如果是这样,那么:

SELECT d.userid,
       d.username,
       det.followupid,
       det.status
FROM   tbl_user_details d
       LEFT JOIN (SELECT userid,
                         followupid,
                         status
                  FROM   tbl_user_followups f
                  WHERE  followupid IN (SELECT Max(followupid)
                                        FROM   tbl_user_followups
                                        GROUP  BY userid)) det
              ON d.userid = det.userid
ORDER  BY det.followupid DESC;


 order by det.followupid desc;

请注意,“按by det.followupid排序”将不能正确地对它们进行排序,因为我们希望某些用户具有“空”的追踪值。