【问题标题】:laravel: error: using join, raw and having in querylaravel:错误:使用连接,原始和查询
【发布时间】:2020-03-21 14:40:45
【问题描述】:

我使用 laravel 框架。我写了这个查询,但它显示了一个错误:

错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'schools.grade' in 'field list' (SQL: select `students`.`name`, `students`.`lastname`, students.id, max(`schools.grade`) as `grade` from `students` inner join `schools` on `schools`.`id` = `students`.`id` group by `schools`.`id` having `grade` = 6)

我的代码:

$stu = students::join('schools', 'schools.id',"=", 'students.id')
            ->select('students.name','students.lastname',DB::raw('students.id, max(`schools.grade`) as `grade`'))
            ->groupBy('schools.id')
            ->having('grade','=',$grade)
            ->get();
        dd($stu);

怎么了? 谢谢

【问题讨论】:

  • 显而易见的问题:schools.grade 存在吗?听起来grade 属于students
  • 是的,schools.grade 绝对存在于表中。

标签: mysql laravel laravel-5


【解决方案1】:

我检查了这两个查询作为测试,它们都单独工作。但可能主查询(我首先提到的)不起作用。

DB::table('schools')
         ->select(DB::raw('id, max(`grade`) as `grade`'))
          ->groupBy('id')
          ->having('grade','=',$grade)
         ->get();

和:

$stu = students::join('schools', 'schools.id',"=", 'students.id')
         ->select('students.name','students.lastname','students.id','schools.grade')
           ->where('schools.grade','=',$grade)  
           ->get();

【讨论】:

    【解决方案2】:

    首先要验证gradeschools 表中是否有列,因为很可能这就是这里的问题。

    如果您认为它确实存在,请尝试在having 条件下使用表名:

    $stu = students::join('schools', 'schools.id',"=", 'students.id')
                ->select('students.name','students.lastname',DB::raw('students.id, max(`schools.grade`) as `grade`'))
                ->groupBy('schools.id')
                ->having('schools.grade','=',$grade)
                ->get();
    dd($stu);
    

    【讨论】:

      【解决方案3】:

      你写的是这样的......

         $stu = students::join('schools', 'schools.id',"=", 'students.id')
              ->select('students.name','students.lastname',DB::raw('students.id,max(`schools.grade`) as `grade`'))
              ->groupBy('schools.id')
              ->having('schools.grade','=',$grade)->get();
          dd($stu);
      

      【讨论】:

        【解决方案4】:
        $stu = students::join('schools as s', 's.id',"=", 'students.id')
                    ->select('students.name','students.lastname','students.id, 
                       DB::raw(max(`s.grade`) as `grade`')) // make sure grade exist in school? if in student then use students.grade in db:Row
                    ->groupBy('s.id')
                    ->having('grade','=',$grade)
                    ->get();
        

        【讨论】:

          猜你喜欢
          • 2017-12-28
          • 2015-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-01
          • 1970-01-01
          • 2018-07-15
          • 2012-10-29
          相关资源
          最近更新 更多