这是您的基本多对多选择语句。
select s.*, t.*
from songs s
join songs_tags st on s.songId = st.songId
join tags t on t.tagId = st.tagId
-- optional where clause
where s.name = 'my song'
当 where 子句基于标签时,翻转它
select s.*, t.*
from tags t
join songs_tags st on s.songId = st.songId
join songs s on s.songId = st.songId
-- optional where clause
where t.name = 'whatever'
如果要返回所有带有多个标签的歌曲,只需更改 where 子句:
select s.*
from tags t
join songs_tags st on s.songId = st.songId
join songs s on s.songId = st.songId
where t.name in ('tag1', 'tag2', 'tag3')
返回带有特定标签的特定歌曲,例如,如果您想按名称和标签搜索
select s.*, t.*
from songs s
join songs_tags st on s.songId = st.songId
join tags t on t.tagId = st.tagId
where s.name like '%mysong%' and t.name in ('tag1', 'tag2')
您还可以过滤连接表本身,有时是必要的:
select s.*, t.*
from songs s
join songs_tags st on s.songId = st.songId
join tags t on t.tagId = st.tagId and t.name in ('tag1', 'tag2')
where s.name like '%mysong%'
查找没有标签的歌曲
select s.*
from songs s
left join songs_tags st on s.songId = st.songId
where st.songId is null
要查找具有所有标签的歌曲:
select s.*
from songs s
join songs_tags st1 on s.songid = st1.songid
join songs_tags st2 on s.songid = st2.songid
join songs_tags st3 on s.songid = st3.songid
where st1.tagid = 1 and st2.tagid = 2 and st3.tagid = 3