MySQL选择具有相同值的3行

时间:2017-06-08 13:35:34

标签: php mysql laravel laravel-5

在我的“赔率”表中,我有多行具有相同的“match_id” 我想每个匹配只选择3行,然后移动另一个匹配,然后再选择3行,依此类推。

想象一下它像不同,但有3行,不仅仅是1。

如果没有laravel 5中的循环,有没有办法做到这一点?

这是我的查询,它使用相同的match_id获取多个(超过3行)。

    \DB::table('matches as m')
  ->select([    'o.id as odd_id',
                'o.match_id as match_id',
                'o.type_id as type_id',
                'o.outcome as outcome',
                'o.odd as odd',
                'm.date_hour as match_date'
            ])
  ->where('m.created_at','>=',\DB::raw('DATE_SUB(NOW(), INTERVAL 24 HOUR)'))
  ->where('m.status_desc_id','=','1')
  ->join('odds as o', function ($join) {
            $join->on('m.id', '=', 'o.match_id')
                 ->where('o.type_id', '=', 43);

        })
  ->groupBy('o.id')
  ->get();

感谢。

2 个答案:

答案 0 :(得分:0)

我认为使用'take(n)'约束会起作用:

\DB::table('matches as m')
  ->select([    'o.id as odd_id',
                'o.match_id as match_id',
                'o.type_id as type_id',
                'o.outcome as outcome',
                'o.odd as odd',
                'm.date_hour as match_date'
            ])
  ->where('m.created_at','>=',\DB::raw('DATE_SUB(NOW(), INTERVAL 24 HOUR)'))
  ->where('m.status_desc_id','=','1')
  ->join('odds as o', function ($join) {
            $join->on('m.id', '=', 'o.match_id')
                 ->where('o.type_id', '=', 43);

        })
  ->groupBy('o.id')
  ->take(3)
  ->get();

答案 1 :(得分:0)

您可以通过为match_id上的每个记录分组生成排名来执行此操作。 然后,您只能检索排名<= 3。

的记录

我使用了我的一个示例表来编写下面的示例查询,它对我有用。( MYSQL

假设SurveyID与您的案例中的match_id相同。 的查询:

Select SurveyId,comments,val,paramid,rank1
From
(
SELECT SurveyId as SurveyId
,a.comments as comments
,a.val as val
,a.paramid as paramid,
(
     CASE SurveyId
     WHEN @curType 
     THEN @curRow := @curRow + 1 
     ELSE @curRow := 1 AND @curType := SurveyId END
     ) AS rank1
FROM test.sample_table a,
(SELECT @curRow := 0, @curType := '') r
) tmp
WHERE rank1 <=3
ORDER BY SurveyId ASC