简体   繁体   English

使用查询生成器使用子选择连接表

[英]JOIN table with subselect using Query Builder

Is it possible to JOIN a subselect with another table in Laravel 5 Query Builder? 是否有可能JOIN与另一个表子查询中Laravel 5查询生成器?

I mean - theoretically - something like this: 我的意思是-从理论上讲-像这样:

$sub = DB::table('A')->select(DB::Raw('id, MAX(date)'))->groupBy('id')->get();

$query = DB::table('B')->join($sub, 'B.id', '=', $sub->id)->get();

In my case, in table A I have duplicated rows. 就我而言,在表A中,我有重复的行。 I need the ones with max date per id . 我需要每个id最大date Then I need to join the result with table B . 然后,我需要将结果与表B联接

As adviced in comments, a workaround follows. 如评论中所建议的,解决方法如下。

$idArray= DB::table('A')->select(DB::Raw('id, MAX(date)'))->groupBy('id')->lists('id');

$query = DB::table('B')->whereIn('id', $idArray)->get();

But, again, just a workaround. 但是,再次,这只是一种解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM