2013-09-28 2 views
0

입니다 생성 :Laravel 4 조합 코드를 잘못 SQL 여기

select * from `topics` inner join `recommends` 
    on `topics`.`id` = `recommends`.`courseid` 
    where `recommends`.`re_type` = ? 
    and `recommends`.`re_location` = ? 
    order by `recommends`.`weigh` desc 
    union //here!!!!! 
    select * from `topics` order by `topics`.`create_time` desc 

오류 정보 :

$f = DB::table("topics") 
      ->join("recommends", "topics.id", "=", "recommends.courseid") 
      ->where("recommends.re_type", "=", $re_type) 
      ->where("recommends.re_location", "=", $re_location) 
      ->orderBy("recommends.weigh", "desc"); 

    $s = DB::table("topics") 
      ->orderBy("topics.create_time", "desc"); 

    $f->union($s)->get(); 

나는 키워드 union 주위에 잘못된 SQL 가지고

SQLSTATE[HY000]: General error: 1221
Incorrect usage of UNION and ORDER BY (SQL: ...)
(Bindings: array (0 => 3, 1 => 7,))

무엇 문제는 무엇입니까?

답변

0

MySQL UNION은 모든 명령문에서 동일한 열을 예상합니다. $f에있는 다른 테이블을 조인하기 때문에 두 문 사이의 열이 일치하지 않습니다.

이 경우

MySql SELECT union for different columns?를 참조하십시오, 그것은 직접 PDO 개체를 사용하는 두통의 작을 수 있습니다.

$pdo = DB::connection()->getPdo(); 
+0

저는 두 가지 쿼리를 모두 보았습니다. 이들은 'select * from topics ...'이고, 다른 컬럼은 없습니다. –

+0

좋은 생각이지만'*'는 테이블마다 다릅니다. 예를 들어,'select topics. *'는 컬럼을 제한하지만 쿼리가 지금 쓰여지기 때문에 두 테이블의 모든 컬럼을 가져옵니다. – Uze

+0

네 말이 맞아! 그냥 테스트하고 MySQL은 두 테이블의 모든 열을 사용합니다. FirebirdSQL은 그렇게하지 않을 것입니다. :/ –

0

검색어에 다른 문제가 있습니다. 당신은 절하여 첫 번째 순서를 재배치해야합니다

->orderBy("recommends.weigh", "desc"); 

그것은 생산하는 order by 당신 union 이전과 MySQL은 받아 들일 수 없습니다.