【问题标题】:How to output data using query builder while eliminating duplicates如何使用查询生成器输出数据同时消除重复
【发布时间】:2017-07-25 14:34:08
【问题描述】:

我有一个结果表,其中有 adm_nosubject_idexam_idscore 字段。我在 laravel 5.4 中使用updateOrCreate 方法插入了数据。

当我获取数据时,我仍然会得到重复的数据。例如当用户为给定学科插入标记(例如 2 个学生)并为相同的学生和学科重复标记时,我应该得到所有结果的最新行。

这是我的查询示例:

public function searchStudent()
{
    $exam = Exam::all();
    $term = Term::all();

    $a = Input::get('adm_no');
    $e = Input::get('exam_id');
    $t = Input::get('term_id');
    $y = Input::get('year');

    $results = DB::table('results')
        ->select(DB::raw('DISTINCT(subject_id)'))
        ->where('adm_no', 'LIKE', '%' . $a . '%')
        ->where('exam_id','LIKE', '%' . $e . '%')
        ->where('term_id', 'LIKE', '%' . $t . '%')
        ->where('year', 'LIKE', '%' . $y . '%')
        ->orderBy('created_at', 'desc')
        ->get();

    dd($results); 
}

【问题讨论】:

    标签: laravel


    【解决方案1】:

    尝试以下查询:

    $results = DB::table('results')
            ->groupBy('subject_id')
            ->where('adm_no', 'LIKE', '%' . $a . '%')
            ->where('exam_id','LIKE', '%' . $e . '%')
            ->where('term_id', 'LIKE', '%' . $t . '%')
            ->where('year', 'LIKE', '%' . $y . '%')
            ->orderBy('created_at', 'desc')
            ->get();
    

    【讨论】:

    • 它仍然没有选择最新的值。假设 adm_no: 1 , subject_id :1 的第一条记录得分为 35,同一学生和科目的第二条得分为 40 我如何在查询中选择 40 并忽略 35。
    • 哦,这有点改变问题,尝试结帐this question
    【解决方案2】:

    我对这个问题进行了更多研究,这就是我为我工作的原因。

    问题

          public function searchStudent(){
            $a= Input::get( 'adm_no' );
            $e= Input::get( 'exam_id' );
            $t= Input::get( 'term_id' );
            $y= Input::get( 'year' );
             $results=DB::table('results')->distinct('subject_id')
            ->where( 'adm_no', $a)
            ->where( 'exam_id', $e)
            ->where( 'term_id',$t)
            ->where( 'year',$y)
            ->groupBy('subject_id')
            ->latest('subject_id')
            ->get();
            dd($results);
              }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-17
      • 2019-04-22
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      相关资源
      最近更新 更多