我有在Laravel中实现的SQL查询。我的疑问是:
SELECT * FROM officer_ranks ra
LEFT JOIN (SELECT * FROM officer_rank_details WHERE void = 0) AS r ON ra.rank = r.present_rank
LEFT JOIN officer_languages l ON r.officer_id = l.officer_id
GROUP BY(ra.rank)
ORDER BY ra.id ASC;
为了实现这个查询,我写道:
DB::table('officer_ranks as ra')
->leftJoin(DB::raw('SELECT * FROM officer_rank_details WHERE void = 0'), 'ra.rank', '=', 'present_rank')
->leftJoin('officer_languages as l', 'officer_id', '=', 'l.officer_id')
->groupBy('ra.rank')
->get();
我的问题是如何将(DB::raw(...))
结果表作为命名r
因为我需要JOIN
个表格。
我尝试使用
leftJoin(DB::raw('SELECT * FROM officer_rank_details WHERE void = 0') as r, 'ra.rank', '=', 'present_rank')
但它没有成功。
答案 0 :(得分:1)
我在评论中写道如何修复你的代码。但是你原来的SQL应该是:
SELECT * FROM officer_ranks ra
LEFT JOIN officer_rank_details AS r
ON ra.rank = r.present_rank
AND r.void = 0
LEFT JOIN officer_languages l ON r.officer_id = l.officer_id
ORDER BY ra.id ASC;
在laravel:
DB::table('officer_ranks as ra')
->leftJoin('officer_rank_details as r', function($join){
$join->on('ra.rank', '=', 'r.present_rank');
$join->on('r.void', '=', 0);
})
->leftJoin('officer_languages as l', 'r.officer_id', '=', 'l.officer_id')
->get();
我还删除了GROUP BY
子句,因为它使用它的方式没有意义。