E
E
Evgeny Skuridin2013-12-27 12:44:12
MySQL
Evgeny Skuridin, 2013-12-27 12:44:12

How to correctly implement SQL many_to_many query?

Hello. Please help with SQL query.
Tables:

categories (id)
videos (id, category_id)
tags (id, title)
videos_tags (id, video_id, tag_id)

You need to pull out all the tags that all videos within a certain category have. The output should have three columns: tag id, tag name, number of videos for this tag (within the category, of course).
It turns out everything except the number of videos by tag. I'm breaking my head, I can't solve the problem myself. I ask the public for help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2013-12-27
@skuridin

SELECT `vt`.`id`, `tg`.`title`, count(`vt`.`id`) FROM `videos` AS `vi` 
    LEFT JOIN `videos_tags` AS `vt` ON `vi`.`id` = `vt`.`video_id`
    LEFT JOIN `tags` AS `tg` ON `vt`.`tag_id` = `tg`.`id`
    WHERE `vi`.`category_id` = id
    GROUP BY `vt`.`id`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question