-1

I create a simple data base on 3 tables: Author, that can has many Books, and Genre that also can has many Books.

enter image description here

I want to get all Genres of one Author using it authorId. I wrote next nested SQL select:

SELECT genre.id, genre.genre_id, genre.genre_name, genre.genre_descr FROM (SELECT book.genre_id FROM book WHERE book.author_id = 7654) AS b JOIN genre WHERE b.genre_id = genre.genre_id;

It works good for me, but is it possible some minimize this select? For example, get rid of nested select?

Yes, I know, that the good solution is to create reference many to many beetwen genre and author, but it will add some complications...

Thanks!

Shadow
  • 33,525
  • 10
  • 51
  • 64
Roman Shmandrovskyi
  • 883
  • 2
  • 8
  • 22

2 Answers2

2

You are almost there. A simple join will do

SELECT DISTINCT g.* FROM genre g JOIN book b ON g.id = b.genre_id AND b.author_id = 7654

If you slow reads, then index on author_id should just work.

Abhijith Nagarajan
  • 3,865
  • 18
  • 23
1

One possible solution without using join:

select * from genre where id in (select genre_id from book where author_id = 7654)
Amir Molaei
  • 3,700
  • 1
  • 17
  • 20