X
X
Xrist1An2015-04-15 20:10:39
MySQL
Xrist1An, 2015-04-15 20:10:39

How to reduce three queries into one?

I have 3 tables:

music (основная)
--
id, path, duration... и т.д.

genre (тут идут названия жанров и их id)
---
genre_id
genre_title

xref_music_genre (а тут отношения id песен из основной таблицы к названию жанра из второй таблицы)
---
music_id
genre_id

All this is necessary in order to make it easier to search for a song by its genre.
But I don’t understand at all how it is now rational to extract a song by genre using 3 tables at once.
The only option that comes to my mind is:
We take all the id of the songs from the relationship table that have the trance genre
SELECT music_id FROM xref_music_genre WHERE genre_title = 'trance'

So, I have all the id of the songs. Now we need to execute a query for each id and pull out a song from the main table. This is already a cycle and a bunch of requests in this cycle for each id. After all, is there any more rational option? How to solve this problem with the help of the 1st request? Could you provide an example of such a request?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Tikhonin, 2015-04-15
@Xrist1An

select m.* from music m, genre g, xref_music_genre mg
where m.id = mg.music_id
and g.genre_id = mg.genre_id
and g.genre_title = 'rock'

A
Andrey Mokhov, 2015-04-15
@mokhovcom

SELECT m.*, GROUP_CONCAT(g.genre_title ORDER BY g.genre_title ASC SEPARATOR'; ') as genre_titles
FROM music m
INNER JOIN xref_music_genre mg ON mg.music_id = m.id
INNER JOIN genre g ON g.genre_id = mg.genre_id
GROUP BY m.id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question