A
A
Alexey Zaitsev2020-01-22 13:23:52
MySQL
Alexey Zaitsev, 2020-01-22 13:23:52

How to pull out all related columns knowing the id of one?

There are related tables. Let's say books, genres and binder "genres of books". Books, of course, can have several genres. How to pull books that have genre "1", while capturing the rest of the genres in one request?
I came to such a decision, "works", but I think there is a more correct, correct solution.

SELECT
b.id, GROUP_CONCAT(g.id) as gid
FROM book b
LEFT JOIN books_genre bg ON bg.books_id = b.id
LEFT JOIN genre g ON g.id = bg.genre_id
GROUP BY b.id
HAVING (FIND_IN_SET(1,gid))

PS if it is possible advise good textbooks on SQL.
Book table structure:
id | name |
1 | book1 |
2 | book2 |
3 | book3 |
Table structure genres:
id | name |
1 | genre1 |
2 | genre2 |
3 | genre3 |
...
The structure of the table genres_books:
id_book | id_genre |
1 | 1
1 | 2
2 | 2
3 | 1
3 | 2
3 | 3
the query result should output:
b.id | guide |
3 | 1,2,3|
1 | 1.2 |
That is, we want to select a fantasy genre and make a query to the database. And he should return to us books with the fantasy genre and also their other genres.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2020-01-22
@Terran37

I would advise the site sql-ex.ru
There exercises on sql from simple to complex. Helps a lot.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question