简体   繁体   中英

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

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:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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