简体   繁体   English

MySQL选择3行相同的值

[英]MySQL select 3 rows with the same value

In my "odds" table I have multiple rows with the same "match_id" I would like to choose only 3 rows per match and then move for another match and again choose 3 rows for that and so on. 在我的“赔率”表中,我有多行具有相同的“ match_id”,我希望每个匹配项仅选择3行,然后移动到另一个匹配项,然后再次选择3行,依此类推。

Imagine it like distinct but with 3 rows, not only 1. 想象一下它像不同的但有3行,不仅是1行。

Is there any way to do it without a loop in laravel 5? laravel 5中有没有循环的方法吗?

Here is my query which takes multiple (more than 3) rows with the same match_id. 这是我的查询,该查询需要多个(超过3个)具有相同match_id的行。

    \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();

Thanks. 谢谢。

I think using the 'take(n)' constraint would work: 我认为使用'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();

You can do this by generating rank for each record grouping on match_id. 您可以通过为match_id上的每个记录分组生成等级来实现。 Then you can retrieve only those records where rank<=3. 然后,您只能检索那些rank <= 3的记录。

I have used one of my sample tables to write below sample query and it worked for me.( MYSQL ) 我已使用我的一个示例表在下面的示例查询中编写了代码,它对我有用。( MYSQL

Assume SurveyID is same as match_id in your case. 假设您的情况下SurveyID与match_id相同。 Query: 查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM