Get first/last n records per group by

后端 未结 4 2060
傲寒
傲寒 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:42

    Much simplified and corrected Carlos solution (his solution would return first 5 rows, not last...):

    SELECT tB1.idA, tB1.idB, tB1.textB
    FROM tableB as tB1
        JOIN tableB as tB2
            ON tB1.idA = tB2.idA AND tB1.idB <= tB2.idB
    GROUP BY tB1.idA, tB1.idB
    HAVING COUNT(*) <= 5
    

    In MySQL, you may use tB1.textB even if it is group by query, because you are grouping by the idB in the first table, so there is only single value of tB1.textB for each group...

提交回复
热议问题