Currently for my website, my articles have tags on them.
When I loop through the list of articles, for each one I do a mysql query to gather a list of category tags for them like so:
SELECT c.`category_name`, c.`category_id`
FROM `articles_categorys` c
INNER JOIN `article_category_reference` r ON c.category_id = r.category_id
WHERE r.article_id = 8136
ORDER BY r.`category_id` = *IDHERE* DESC, r.`category_id` ASC
LIMIT 4
Now, imagine a page where I have say 30 articles shown at once, the above query would be done 30 times. I imagine that's terrible.
What I decided to do was make an array of all the article_ids on a page and then do this instead:
SELECT c.`category_name`, c.`category_id`, r.article_id
FROM `articles_categorys` c
INNER JOIN `article_category_reference` r ON c.category_id = r.category_id
WHERE r.article_id = 8136 OR r.article_id = 8130 OR r.article_id = 8127
OR r.article_id = 8125 OR r.article_id = 8123 OR r.article_id = 8120
OR r.article_id = 8119 OR r.article_id = 8117 OR r.article_id = 8116
OR r.article_id = 8112 OR r.article_id = 8107 OR r.article_id = 8106
OR r.article_id = 8037 OR r.article_id = 8104 OR r.article_id = 8103
I then use PHP just to loop through the array found from the above, match the article_id to the current article to them and if it matches echo the category_name. The only problem is now I can't limit it to 4 per article_id.
Is the newer approach better, worse, or do both suck horribly?
Example data to use:
CREATE TABLE `articles_categorys` (
`category_id` int(11) NOT NULL,
`category_name` varchar(32) COLLATE utf8_bin NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `article_category_reference` (
`ref_id` int(11) NOT NULL,
`article_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `articles_categorys` (`category_id`, `category_name`) VALUES
(22, 'Site Info'),
(1, 'Editorial'),
(2, 'Review'),
(3, 'Interview'),
(4, 'Game Sale'),
(5, 'Steam'),
(6, 'Indie Game'),
(7, 'Crowdfunding'),
(8, 'Game Bundle'),
(9, 'Free Game'),
(10, 'MMO');
INSERT INTO `article_category_reference` (`ref_id`, `article_id`, `category_id`) VALUES
(15, 6231, 22),
(14, 6231, 1),
(16, 6231, 2),
(17, 6231, 3),
(18, 6231, 4),
(19, 6231, 9),
(20, 6231, 10);