laravel where子句中的子查询

时间:2017-10-24 07:00:46

标签: mysql laravel laravel-5 laravel-5.3

我想在where子句中使用mysql编写子查询。如果可以在laravel的where子句中使用子查询

SELECT
    p.*, d.name, d2.name, d2.head, u.id, u.aceid, u.firstname
FROM project as p
left join department as d
    on p.department_string_id = d.string_id
left join department as d2
    on d.parent_department_string_id = d2.string_id
LEFT join users as u
    on d2.head_aceid = u.aceid
where p.code in
(select ar.project_code from asset_request as ar
 where ar.request_id= '1718AM0010')

在laravel我尝试过

DB::table('project as p')   
                ->leftJoin('department as d','p.department_string_id','=','d.string_id')
                ->leftJoin('department as d2','d.parent_department_string_id','=','d2.string_id')
                ->leftJoin('users as u','d2.head_aceid','=','u.aceid')
                ->where('p.code','=','USA_0057_07')  //instead of code need to use subquery
                ->select('u.id')
                ->first();

2 个答案:

答案 0 :(得分:1)

DB::table('project as p')   
    ->leftJoin('department as d','p.department_string_id','=','d.string_id')
    ->leftJoin('department as d2','d.parent_department_string_id','=','d2.string_id')
    ->leftJoin('users as u','d2.head_aceid','=','u.aceid')
    ->whereRaw("p.code in (select ar.project_code from asset_request as ar where ar.request_id= '1718AM0010')")
    ->select('u.id')
    ->first();

答案 1 :(得分:1)

我认为你可以重构你的查询,用另一个连接替换WHERE子句中的子查询:

SELECT
    p.*, d.name, d2.name, d2.head, u.id, u.aceid, u.firstname
FROM project as p
LEFT JOIN department as d
    ON p.department_string_id = d.string_id
LEFT JOIN department as d2
    ON d.parent_department_string_id = d2.string_id
LEFT JOIN users as u
    ON d2.head_aceid = u.aceid
INNER JOIN asset_request ar
    ON p.code = ar.project_code
WHERE
    ar.request_id = '1718AM0010'

Laravel代码:

DB::table('project as p')   
            ->leftJoin('department as d','p.department_string_id', '=', 'd.string_id')
            ->leftJoin('department as d2', 'd.parent_department_string_id', '=', 'd2.string_id')
            ->leftJoin('users as u', 'd2.head_aceid', '=', 'u.aceid')
            ->join('asset_request as ar', 'ar.project_code', '=', 'p.code')
            ->where('ar.request_id', '=', '1718AM0010')
            ->select('u.id')
            ->first();