2011-04-01 99 views
0

嗨 我是新來的SQL,所以想知道你們是否可以幫助我。幫助與SQL查詢

我有4個表

  • 藝術家(artistID,...)
  • 專輯(ALBUMID,artistID,...)
  • 歌(songID,...)
  • albumsongs (songID,ALBUMID)

以及連接多對多的專輯和歌曲之間的表 - albumsongs

基本上在我的albumsongs表中我有一個歌曲ID和一個專輯ID。

在專輯表中我有一個artistID。

我想列出屬於特定藝術家的每首歌曲,即使它們之間沒有直接的外鍵引用。從藝術家到歌曲的唯一真正的聯繫是通過專輯。這可能與某種先進的查詢魔術?

+0

是否歌曲或專輯是指藝術家? – n8wrl 2011-04-01 20:14:24

+0

@ n8wrl專輯表有一個artistID,我在OP中提到過。 – 2011-04-01 20:15:33

回答

7

聽起來像一個簡單的多表連接:

select artist.name, album.title, song.title 
from artist 
    inner join album on album.artistid = artist.artistid 
    inner join albumsongs on albumsongs.albumid = album.albumid 
    inner join songs on songs.songid = albumsongs.songid 
where artist.name = 'Pere Ubu' 
+0

打敗我吧。我即將發佈幾乎相同的代碼。 – 2011-04-01 20:21:11

+0

+1 - 打我也:) – JNK 2011-04-01 20:22:04

+0

添加Where語句以檢查所需的藝術家。 – 2011-04-01 20:23:45

2
select distinct sng.* 
from song sng 
inner join albumsongs a_s on a_s.song_id = sng.id 
inner join album alb on alb.id = a_s.album_id 
inner join artist art on art.id = alb.artist_id 
where art.name like '%NAME_CRITERIA_HERE%' 

select * from song where id in (
    select a_s.song_id 
    from albumsongs a_s 
    inner join album alb on alb.id = a_s.album_id 
    inner join artist art on art.id = alb.artist_id 
    where art.name like '%NAME_CRITERIA_HERE%' 
)