I have news table from where I need to select specific number or rows - for example 3 news from 4 categories. There should always be 3 news from each category (table is full of contents - it's not the matter). I want to select only the newest ones.
Suppose my table contains 5 fields: id_news, news_title, news_desc, news_date, id_news_category.
Edit: Looks like those previous questions can't help me because what I really need to do is to select top N from range of categories id, for eg. 1-6, 7-13, 14-20 etc.
I'm looking for the best (most efficient) way to accomplish this. Is it UNION operator:
SELECT id_news, news_title
FROM news
WHERE id_news_category BETWEEN 1 AND 6
ORDER BY news_date DESC
LIMIT 3
UNION
SELECT id_news, news_title
FROM news
WHERE id_news_category BETWEEN 7 AND 13
ORDER BY news_date DESC
LIMIT 3
UNION
SELECT id_news, news_title
FROM news
WHERE id_news_category BETWEEN 14 AND 20
ORDER BY news_date DESC
LIMIT 3
UNION
SELECT id_news, news_title
FROM news
WHERE id_news_category BETWEEN 21 AND 27
ORDER BY news_date DESC
LIMIT 3
I know above UNION may have quite other form - with single order. Not really sure if it has performance impact. I'm using PSql 8.4 and Symfony so I will need to use QueryBuilder or maybe just native query.