2017-11-18 171 views
0

如何在laravel中執行這個sql查詢?三個表sql查詢Laravel查詢

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查詢嗎?

感謝

回答

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...]); 

也可能更快地加入(但機會是數據庫管理系統具有優化,其中查詢作爲聯接的一種方式)。