I have 2 tables, category and articles, I want to get 5 articles for each category, the tables look like this:
category: id, name
articles: id, title, body, category_id
So what I normally do is INNER JOIN, but I get all rows, how can I specify that I need only 5 rows per category, I imagine it would need a SELECT within a SELECT ?
You can use a rank query mysql does not have window functions for this type of results to get n records per group,i will not suggest a
group_concat
solution because asarticles
terms says that there can be enough data and easily by pass the 1024 character limit constraint if you increase this limit it also has a dependency onmax_allowed_packet
tooAbove will rank each article within in its category group you can see the result of
rownum
alias and in outer query just filter the results of articles to 5 per category groupYou can hack your query using
group_concat
in MySQL since MySQL does not support windows functions unfortunately. It won't look pretty though.You can use this blog post as inspiration to build the query you need.
Other possibility is to retrieve every article in category and filter the top 5 yourself at the client side (PHP, Java, Python, you name it).