Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select 3 row per category in MySQL?

I have a table which have a lot of data, it's have a category ID and postId, I need to read 3 new post per category with same CatID.

it's not duplicate of the question suggest by other people. Please check that in my question the postid catid can be anything when in duplicate question it's calculate before running query.

What I have written is

SELECT
    MAX(` postid `) AS p1,
    ` catid ` AS c1
FROM
    ` postcategory `
GROUP BY
    ` catid

I can put 2 other query in it union distinct but it will make a query a lot big. Is there any good way to do this in MySQL. What I am looking for reading 3 postId (maximum) belong to same category.

postId   catId  
------  --------
     9         3
    15         3
    16         3
    17         3
    18         3
    19         5
    20         8
    21         6
    22         8
    23         6
    46         6
    46         8
    26         3
    25         3
    27         5
    28         3
    37         6
    39        10
    40         6
    41         6
    42         6
    43         6
    44         5
    45        11
    63         6
    64         5
    65         6
    66         6
    68         6
like image 655
Anirudha Gupta Avatar asked Mar 11 '23 12:03

Anirudha Gupta


1 Answers

You can read 3 new post from each category Using the below query.

SELECT
    p1.postId,
    p1.catId
FROM
    postcategory p1
JOIN postcategory p2 ON p1.catId = p2.catId
AND p2.postId >= p1.postId
GROUP BY
    p1.postId,
    p1.catId
HAVING
    COUNT(*) <= 3
ORDER BY
    catId,
    postId

Here you can see the Live Demo

Output:

enter image description here

like image 152
Faisal Avatar answered Mar 20 '23 03:03

Faisal