Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 Database Design and Application Architecture
 Need help with query - joining 3 tables

Author  Topic 

webchris
Starting Member

2 Posts

Posted - 2011-08-28 : 19:27:09
I am familiar with joining tables, but this particular setup has really gotten to me. I don't know if I'm overthinking it or what. Here is an example of my structure:

Songs
ID | Song_Name

Genres
ID | Genre_Name

Groups
ID | Group_Name

Song_Genres (links songs table to genres table)
Song_ID | Genre_ID

Group_Linking (links groups table to genres table)
Genre_ID | Group_ID


I have genre "groups" where you might combine country and western, or rap and r&b into a similar group to pull together. Each song can be listed in multiple genres, and each genre can be in multiple groups. That's why I need the 2 linking tables.

Now what I am trying to do is pull all songs that are in group 1. It sounds really easy, but I am not able to wrap my head around it yet. I tried the simplest way I could think of, but its duplicating my song for each genre its in.

SELECT songs.id, songs.song_name FROM songs, song_genres, group_linking WHERE songs.id = song_genres.song_id AND song_genres.genre_id = group_linking.genre_id AND group_linking.group_id = 1

I think I need a LEFT JOIN but not sure how to do that with the 3 tables. Any help would be greatly appreciated!

GilaMonster
Master Smack Fu Yak Hacker

4507 Posts

Posted - 2011-08-28 : 19:37:45
FROM Songs WHERE ID IN (select Song_ID from Song_Genres inner join Group_Linking ON Song_Genres.Genre_ID = Group_Linking.Genre_ID WHERE Group_ID = 1)

Easiest way to get the songs without duplication. If you join you'll have to eliminate the duplicates that the join creates.


--
Gail Shaw
SQL Server MVP
Go to Top of Page

webchris
Starting Member

2 Posts

Posted - 2011-08-28 : 19:56:56
Thanks GilaMonster! That was perfect, and I learned something. :)
Go to Top of Page

GilaMonster
Master Smack Fu Yak Hacker

4507 Posts

Posted - 2011-08-28 : 20:55:49
Good. Now, for additional credit, figure out how to rewrite that with EXISTS instead of IN :-)

Hint: http://sqlinthewild.co.za/index.php/2009/08/17/exists-vs-in/

--
Gail Shaw
SQL Server MVP
Go to Top of Page
   

- Advertisement -