2013-09-28 62 views
0

这里是代码:Laravel 4工会产生错误的SQL

$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:

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 

错误信息:

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不会接受。