A
A
alexanderqwert2018-10-22 18:37:24
MySQL
alexanderqwert, 2018-10-22 18:37:24

How to get articles from the database capturing different categories as much as possible?

There is a table with articles articles that belong to different categories by category_id.
It is necessary to return a certain number of articles (say 10), in order to capture as many categories as possible to which they belong, for example
, if I have 5 categories, then I will be returned 2 articles from each category 5* 2=10
if there are 10 categories, then one article from each category will be returned to me ;
if there are 2 categories, then 5 articles from each will be returned
how to do this?
UPD:
if there are 10 categories and 5 articles, then the first 5 categories for 1 article will be
returned UPD2:
articles table:
id, category_id, title, body

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Uspensky, 2018-10-22
@alexanderqwert

I didn’t think about optimality, but keep it

select id,
       category_id,
       title,
       row_number() over(partition by category_id) as rownum
from articles
order by rownum
limit 10;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question