PHP / MySQL - select one of each type in the table
I am creating a blog with many different categories, and on my home page I would like to show one post from each category (except maybe the "buggy" one), but I'm not sure if there is a simple one-line solution for this. I am hoping for something like:
"SELECT * FROM blogs WHERE cat != 'misc' ORDER BY added LIMIT (ONE OF EACH CAT TYPE)"
Is this possible?
source to share
You can try GROUP BY
your own category. more on GROUP BY
https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
SELECT * FROM blogs WHERE cat != 'misc' GROUP BY cat ORDER BY added
source to share
If you want to find the newest post in each category, you will need to figure out which post is the newest and then join it - you can do this with a subquery if necessary:
SELECT b.*
FROM blogs `b`
INNER JOIN (SELECT `category`, MAX(`added`) AS `max_add` FROM `blogs` GROUP BY `category` WHERE `category` != 'misc') `a`
ON `a`.`category` = `b`.`category` AND `a`.`max_add` = `b`.`added`
(or something similar - it's best to join a PC if possible)
This question provides a fairly detailed answer to a common problem.
source to share