首页 > 解决方案 > 如何从连接表中获取基于多个条件的歌曲

问题描述

我有两张表songsong_clubs。架构如下:-

songs schema
 id        available_for      song_name     status
 1           all                 Song 1      1
 2          selection            Song 2      1
 3          selection            Song 3      1
song_clubs schema
song_id     club_id
 2            1
 2            2
 3            2

现在我想获取俱乐部 id 1的歌曲,并且该歌曲适用于所有俱乐部。我的执行输出如下:-

id        available_for      song_name
 1           all                 Song 1
 2          selection            Song 2

我试过下面的查询

select id,available_for,song_name from songs 
 JOIN 
song_clubs
on song_clubs.song_id = songs.id
WHERE songs.status =1 and song_clubs.club_id=1 or songs.available_for ='all'

但它只返回一个基于选择的条目。

标签: mysqlsqljoinsubqueryexists

解决方案


你可以这样做EXISTS

SELECT s.id, s.available_for, s.song_name 
FROM songs s
WHERE s.status =1 AND (  
      s.available_for = 'all' 
   OR EXISTS (SELECT 1 FROM song_clubs c WHERE c.club_id = 1 AND c.song_id = s.id))

或与操作员IN

SELECT id, available_for, song_name 
FROM songs 
WHERE status =1 AND (
      available_for = 'all' 
   OR id IN (SELECT song_id FROM song_clubs WHERE club_id = 1))

推荐阅读