2016-11-18 116 views
0

我使用laravel 5.3,並且我在laravel查詢方法中有一些左連接查詢錯誤。 這是我的正常查詢Laravel左加入查詢

SELECT bran.branchName,sch.schoolName From m_schoolbranch bran 
LEFT JOIN m_students stu ON stu.schoolNo=bran.schoolNo AND stu.branchNo=bran.branchNo 
LEFT JOIN m_school sch ON sch.schoolNo=stu.schoolNo where stu.userNo='0000000001'; 

這是我的新laravel查詢

DB::table('m_schoolbranch') 
      ->join('m_students', 'm_schoolbranch.schoolNo', '=', 'm_students.schoolNo') 
      ->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo') 
      ->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo') 
      ->select('m_school.schoolName', 'm_schoolbranch.branchName') 
      ->where('m_students.userNo',$userNo) 
      ->get(); 

在這些查詢我需要匹配表m_students兩名欄,所以我把這樣的

->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo') 

但我顯示錯誤...

+0

什麼錯誤說? – RustamG

+0

Connection.php中的QueryException 729行: SQLSTATE [42000]:語法錯誤或訪問衝突:1066非唯一表/別名:'m_students'(SQL:select'm_school'.'schoolName','m_schoolbranch'.'ranchName'從'm_schoolbranch'內連接'm_students'在'm_schoolbranch'.'schoolNo''''m_students'.'schoolNo'內連接'm_students'在'm_schoolbranch'.'branchNo' ='m_students'.'branchNo' inner join'm_school ''m_schoolbranch'.'schoolNo' ='m_school'.'schoolNo' where'm_students'.'userNo' = 0000000001) –

回答

0

查詢中的表需要具有唯一的n否則在評估m_schoolbranch.schoolNo時,DB無法知道應使用哪個m_schoolbranch

您可以在連接語句中使用唯一的表別名,但我建議在連接上使用多個條件。就像您在原始SQL查詢中使用一樣。看到這裏:https://stackoverflow.com/a/20732468/4437888

+0

Thnx我用你的代碼解決了它。 –

0
DB::table('m_schoolbranch') 
      ->join('m_students', function($join) 
       { 
        $join->on('m_schoolbranch.schoolNo', '=', 'm_students.schoolNo'); 
        $join->on('m_schoolbranch.branchNo', '=', 'm_students.branchNo'); 
       }) 
      ->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo') 
      ->select('m_school.schoolName', 'm_schoolbranch.branchName') 
      ->where('m_students.userNo',$userNo) 
      ->get();