【问题标题】:Laravel 4 union generate wrong SQLLaravel 4联合生成错误的SQL
【发布时间】:2013-10-04 20:02:00
【问题描述】:

代码如下:

    $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]:一般错误:1221
UNION 和 ORDER BY 的错误用法(SQL: ...)
(绑定:数组( 0 => 3, 1 => 7, ))

有什么问题?

【问题讨论】:

    标签: php mysql laravel laravel-4


    【解决方案1】:

    MySQL UNION 要求所有语句中的列相同。因为您要加入 $f 中的另一个表,所以两个语句之间的列不匹配。

    MySql SELECT union for different columns?

    在这种情况下,直接使用 PDO 对象可能不会那么令人头疼。

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

    【讨论】:

    • 我不这么认为,看两个查询,都是select * from topics...,没有其他列。
    • 好主意,但 * 不是特定于表的。例如,select topics.* 会限制列,但现在编写查询时,它将获取两个表中的所有列。
    • 你是对的!刚刚对其进行了测试,MySQL 使用了两个表中的所有列。 FirebirdSQL 不会那样做。 ://
    • @AntonioCarlosRibeiro 这绝对是一个令人沮丧的功能。出于类似的原因,我尽可能避免在查询中使用星号。
    【解决方案2】:

    发现您的查询存在另一个问题。您应该重新定位您的第一个 order by 子句:

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

    它在union 之前生成order by 你,MySQL 不会接受。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-30
      • 2016-11-03
      • 2014-05-21
      • 2014-05-09
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多