I have the following query:
SELECT m.*, COUNT(c.chapter_nr) as chapters, MAX(c.chapter_nr) as latest_chapter
FROM comic_series AS m
JOIN chapters as c on c.comic_id = m.id
WHERE m.title_en = 'test'
This allows to me to find the chapters from a comic book by just giving the name of the comic. The query selects all the columns from the comic_series
table and adds the chapters
(number of chapters for that comic) and latest_chapter
(newest chapter) columns.
Now, the problem that's bugging me for quite a while:
I have a third column which contains the comic IDs linked to categories IDs (and the category details are in a fourth table but this is irrelative here), and I'd like to select the comic books and their chapters by searching for category IDs.
This is what I've come up with so far:
SELECT `m`.*, COUNT(c.chapter_nr) as chapters, MAX(c.chapter_nr) as latest_chapter
FROM `comic_series` AS `m`
JOIN `comic_categories` AS `mc` ON mc.comic_id = m.id
JOIN chapters as c on c.comic_id = m.id
where mc.category_id = 5
GROUP BY `m`.`id`
And this returns the correct COUNT(c.chapter_nr)
but when I add more category IDs it returns an incorrect amount:
SELECT `m`.*, COUNT(c.chapter_nr) as chapters, MAX(c.chapter_nr) as latest_chapter
FROM `comic_series` AS `m`
JOIN `comic_categories` AS `mc` ON mc.comic_id = m.id
JOIN `chapters` as c on c.comic_id = m.id
where mc.category_id = 5 OR mc.category_id = 1
GROUP BY `m`.`id`
The query above should return 1 for COUNT(c.chapter_nr)
but it returns 2. This could maybe be because there are 2 records in the comic_categories
table for that comic and only 1 record in the chapters
table.