如何在Laravel 5.1中运行这个更复杂的查询?

时间:2015-11-17 01:52:03

标签: php laravel laravel-5 laravel-5.1

我似乎无法使用查询构建器或原始查询来弄清楚如何在laravel中运行它。

SELECT table1.*, table2.* 
FROM table1
INNER JOIN (
    SELECT id, MAX(date) as date FROM table1 group by id
) as tb1 ON tb1.id = table1.id and tb1.date = table1.date
INNER JOIN table2 ON table2.id = table1.id 
where table2.id in(1,2,3)

我试过的查询:

注意:这些不是确切的查询,它们可能包含错误,但它们代表了我尝试过的要点

$players = \DB::select(
  'SELECT table1.*, table2.* FROM table1
   INNER JOIN (
     SELECT id, MAX(date) as date FROM table1 group by id
   ) as tb1 ON tb1.id = table1.id and tb1.date = table1.date
   INNER JOIN table2 ON table2.id = table1.id where table2.id in(1,2,3)');
$table->select('SELECT table1.*, table2.* FROM table1')
      ->join(\DB::raw('INNER JOIN ( SELECT id, MAX(date) as date FROM table1 group by id ) as tb1', function($join){
          $join->on('tb1id', '=', 'table1.id')->where('tb1.date','=','table1.date')
      })
      ->join('table2', function($join){
          $join->on('table2.id', '=', 'table1.id')->whereIn('table2.id',[1,2,3])
      });

所以,愚蠢的我,第一个\ DB :: select(...)查询将起作用,我有一个调试器行在那里捕获查询。我还在想是否有 是另一种方法。

0 个答案:

没有答案