多对多关系SQL查询

Goo*_*oey 3 mysql

我正在尝试创建一个可以在多对多关系数据库中获取结果的查询。
到目前为止,我得到了以下内容:
一张带有歌曲的表,一张带有标签的表和一个“链接”表,因为一首歌曲可以有多个标签,而一个标签可以属于多首歌曲。

它看起来像这样:

Songs       Link        Tags
=======     =====       =========
Sid          Sid        Tid
Songname     Tid        Tagname
Run Code Online (Sandbox Code Playgroud)

现在假设您有 3 首歌曲 AB 和 C 以及 3 个标签:X、Y 和 Z。
歌曲 A 有标签 Y,歌曲 B 有标签 Z,歌曲 C 有标签 X 和 Z。

我设法创建了一个查询以仅通过一个标签获取一首歌曲(例如 Z 给出 B 和 C)。
但是,当输入多个标签(例如,输入到(搜索)字段中)时,我如何创建一个搜索歌曲的查询。

我已经搜索过几次命令 INTERSECT 和 INNER JOIN 出现了,但我还没有能够成功地创建一个查询。

任何帮助表示赞赏!

Chr*_*ler 5

这是您的基本多对多选择语句。

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'
Run Code Online (Sandbox Code Playgroud)

当 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'
Run Code Online (Sandbox Code Playgroud)

如果要返回带有多个标签的所有歌曲,只需更改 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')
Run Code Online (Sandbox Code Playgroud)

返回带有特定标签的特定歌曲,例如,如果您想按名称和标签进行搜索

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')
Run Code Online (Sandbox Code Playgroud)

您还可以过滤连接表本身,有时是必要的:

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%'
Run Code Online (Sandbox Code Playgroud)

查找没有标签的歌曲

select s.*
from songs s
left join songs_tags st on s.songId = st.songId
where st.songId is null
Run Code Online (Sandbox Code Playgroud)

要查找具有所有标签的歌曲:

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
Run Code Online (Sandbox Code Playgroud)