Get first/last n records per group by

后端 未结 4 2066
傲寒
傲寒 2021-01-01 00:12

I have two tables : tableA (idA, titleA) and tableB (idB, idA, textB) with a one to many relationship between them. For each row in tableA, I want

4条回答
  •  粉色の甜心
    2021-01-01 00:26

    Ensure your "B" table has an index on ( idA, idB ) for optimized order by purposes so for each "A" ID, it can quickly have the "B" order descending thus putting the newest to the top PER EACH "A" ID. Using the MySQL variables, every time the "A" ID changes, it resets the rank back to 1 for the next "A" id.

    select 
          B.idA,
          B.idB,
          B.textB
          @RankSeq := if( @LastAGroup = B.idA, @RankSeq +1, 1 ) ARankSeq,
          @LastAGroup := B.idA as ignoreIt
       from
          tableB B
             JOIN tableA A
                on B.idA = A.idA,
          (select @RankSeq := 0, @LastAGroup := 0 ) SQLVars 
       having
          ARankSeq <= 5
       order by
          B.idA,
          B.idB DESC
    

提交回复
热议问题