How to implement the interface that returns the first N pieces of data for each category?

problem description

for example, there is an information table in mysql, each piece of data contains name and categoryId, and a table of category names, including categoryId and categoryName.
now there is an interface requirement to return the first N pieces of data under all categories, probably in this form
[

{
    "categoryId":1001,
    "data":[
        {
            "name":"test1"
        },
        {
            "name":"test2"
        }
    ]
},
{
    "categoryId":1002,
    "data":[
        {
            "name":"test3"
        },
        {
            "name":"test4"
        }
    ]
}

]

because the number of categories is not fixed, each category may have to access the database many times at a time. The current practice is to write a complex sql to check them all at once, and it can also be done. But I am afraid that the performance of sql cannot be guaranteed if there is a large amount of data in the future. Is there any other more general method that can be used for reference?

May.22,2021

Classification table gets all categories id,
loop, query the first number of items of each category separately, put in list
and return finally.


if you want to consider performance, of course, it is caching.
redis learn about

.
Menu