dtqu72830 2017-06-08 13:35
浏览 44
已采纳

MySQL选择具有相同值的3行

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.

Imagine it like distinct but with 3 rows, not only 1.

Is there any way to do it without a loop in laravel 5?

Here is my query which takes multiple (more than 3) rows with the same 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.

  • 写回答

2条回答 默认 最新

  • douyue8191 2017-06-08 14:04
    关注

    You can do this by generating rank for each record grouping on match_id. Then you can retrieve only those records where rank<=3.

    I have used one of my sample tables to write below sample query and it worked for me.(MYSQL)

    Assume SurveyID is same as match_id in your case. 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?
  • ¥15 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用
  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启