2014-10-10 37 views
1

我正在製作一個音樂下載網站。在這裏有三個名爲song_tbl,artist_tbl,album_tbl的表。
Song_tbl
enter image description here如何在Mysql中關聯表格

Artist_tbl
enter image description here

Album_tbl
enter image description here

的每首歌曲的藝術家。但問題是,有些歌曲有不止一個藝術家(例如:歌曲2可能有兩個藝術家=彼得森和藝術家3)。那我該如何管理呢?謝謝你的幫助。

+1

這看起來像一個M到N的關係,所以你必須創建一個SongID表Song_Artist和ArtistID爲外鍵。 – Patrick 2014-10-10 08:12:25

+0

意味着我必須創建第四張表Song_Artist,我不需要刪除artist_tbl? – shiv 2014-10-10 08:18:39

+1

是的,多數民衆贊成在藝術家表中,您擁有所有藝術家,在歌曲歌曲和Song_Artist_Tbl中只有歌曲和藝術家之間的關係,所以您可以讓歌曲2由歌手1演唱,下一首歌曲2是由藝術家xy唱歌。 – Patrick 2014-10-10 08:22:36

回答

1

您需要有一張表song_artist_tbl將歌曲鏈接到藝術家。它應該有2列:song_id和artist_id,然後,如果歌曲2鏈接到藝術家2和3,您有:

song_artist_tbl 
song_id artist_id 
2   2 
2   3 

然後你可以從song_tbl表中刪除artist_id列

+0

我也想過這個。這意味着在這張表中,我將擁有與song_tbl表中相同的行。我對嗎? – shiv 2014-10-10 08:13:12

+1

如果某些歌曲擁有多個藝術家,則可能會有更多的行。 – CCH 2014-10-10 08:14:22

+0

謝謝@ CCH先生幫助我。 – shiv 2014-10-10 08:30:29

1

刪除從song_tblartist_id列,並添加一個新的表名爲song_artists_tbl

song_artists_tbl 
---------------- 
song_id 
artist_id 

它被稱爲1-n的關係。

實例數據將

song_id | artist_id 
1  | 1 
1  | 2 
+0

謝謝@先生juergen d幫助我。 – shiv 2014-10-10 08:31:00

+0

謝謝先生@juergen d幫助我。 – shiv 2014-10-10 08:39:02

1

您使用一個多對多的關係用一個鏈接表。

你最終得到一個只包含引用表的鍵的song_artist表。

實施例:

song_tbl: song_id album_id ...

album_tbl: album_id ...

artist_tbl: artist_id ...

artist_song_tbl: song_id artist_id

有了這個設置,你可以有一首歌曲,許多藝術家在播放它。

對於進一步閱讀: http://www.tomjewett.com/dbdesign/dbdesign.php?page=manymany.php

+0

謝謝@先生macanuga幫助我。 – shiv 2014-10-10 08:36:58