2011-01-21 62 views
1

我有两个表:我应该使用什么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 

我有兴趣在给予user_id我返回所有他们所拥有的歌曲进行查询。例如,您可以看到用户28拥有两首歌曲。

顺便说一句,这是最好的我知道如何规范化这张表,并且对如何更常规地存储这些数据(我只是在学习SQL)提出建议。这是一个典型的表设置?

回答

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

假设同一个用户不能拥有同一首歌两次。你的规范化看起来很好!您的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=?