2011-01-21 8 views
1

私は2つのテーブルがあります:私は、私は、彼らが所有するすべての曲を返されていuser_id特定のクエリを実行することに興味使用するSQL操作は何ですか?

TABLE 'songs' 
song_id --some other columns about this song 
------- 
1 
2 
3 

TABLE 'song_ownership' 
user_id  song_id 
-------  ------- 
28   1 
28   3 
538   1 
234   2 

を。たとえば、ユーザー28が2曲を所有していることがわかります。

ちなみに、これは私がこのテーブルを正規化する方法を知っている最善の方法であり、このデータをより慣習的に格納する方法についての提案を公開しています(私はSQLを学んでいます)。これは典型的なテーブル設定ですか?

答えて

3
select songs.* 
from songs 
inner join song_ownership on song_ownership.song_id = songs.song_id and  
[email protected]_id 

同じユーザーが同じ曲を2回所有できないとします。あなたの正規化はこれまでのところよく見えます!あなたのsong_ownershipテーブルは「多対多」テーブルになります(ソング・ユーザーの関連付けが一意の場合)。両方の列に複合主キーを置くと、ユーザーは別のテーブルに置かれます。

+0

+1は私の質問に賛成です! :-) – InSane

1
select * -- choose only the columns you're interested to, like user id and song name 
from songs 
    inner join song_ownership on song_ownership.song_id=songs.song_id 
where song_ownership.user_id=? 
関連する問題