Answer the question
In order to leave comments, you need to log in
How to select the last 5 records of each category with one query in MySQL?
Hello.
Let's say we have a table with the following structure: id, cid, title.
Is there some elegant way to select the last 5 entries of each category (cid) in one query?
Answer the question
In order to leave comments, you need to log in
We try. All measurements on a table with 5000 records, random cid from 1 to 10, id primary, per cid index.
On PostgreSQL you can query
SELECT a.*
FROM somedata AS a
WHERE a.id IN (
SELECT b.id
FROM somedata AS b
WHERE b.cid = a.cid
ORDER BY b.id DESC
LIMIT 5
)
ORDER BY a.cid DESC, a.id DESC
SELECT a.*
FROM somedata AS a
WHERE a.id IN (
SELECT id
FROM somedata AS b
WHERE b.cid = a.cid AND (SELECT COUNT(*) FROM somedata AS c WHERE c.id >= b.id AND c.cid = b.cid) <= 5
)
ORDER BY a.cid DESC, a.id DESC
(SELECT * FROM somedata WHERE cid = 1 ORDER BY id DESC LIMIT 5)
UNION
(SELECT * FROM somedata WHERE cid = 2 ORDER BY id DESC LIMIT 5)
UNION
(SELECT * FROM somedata WHERE cid = 3 ORDER BY id DESC LIMIT 5)
Try:
SELECT `t1`.`id`, `t1`.`cid`, `t1`.`title`, COUNT(*) as `counter` FROM `test` `t1` JOIN `test` `t2` ON `t1`.`cid` = `t2`.`cid` AND `t1`.`id` >= `t2`.`id` GROUP BY `t1`.`cid`, `t1`.`id` HAVING `counter` <= 5 ORDER BY `t1`.`cid`, `t1`.`id`;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question