三个表Sql查询到Laravel查询

时间:2017-11-18 07:58:13

标签: sql laravel

如何在laravel中执行此sql查询?

  SELECT * FROM `examination` WHERE `id` in (select `exam_id` from
 `exam_supervision`  where `lecturer_id` in (select `id` from `lecturers` where `id`=1));

Laravel看起来很混乱。任何人都可以给我一个确切的laravel查询?

感谢

1 个答案:

答案 0 :(得分:0)

您可以在whereIn次查询中使用闭包。

DB::table("examination")->whereIn("id", function ($query) {
        return $query->select("exam_id")
             ->from("exam_supervision")->select("exam_id")
             ->whereIn("lecturer_id", function ($query) {
                     return $query->select("id")
                               ->from("lecturers")
                               ->where("id", 1);
             });
});

然而,等效语法可能更简单:

 DB::table("examination")
     ->join("exam_supervision", "examination.id", "exam_supervision.exam_id")
     ->join("lecturers", "exam_supervision.lecturer_id", "lecturers.id")
     ->where("lecturers.id", 1) 
     ->select(["examination.col1", "examination.col2...]);

加入也可能更快(但DBMS有可能优化whereIn查询作为连接)。