mysql - 如何从连接表中获取基于多个条件的歌曲
问题描述
我有两张表song和song_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'
但它只返回一个基于选择的条目。
解决方案
你可以这样做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))
推荐阅读
- javascript - ( Html2Canvas & jsPDF ) 为什么用 chrome 剪切图像?(在 safari 中不会被切断。)
- amazon-web-services - 有没有办法将文件大小作为输入参数从 AWS S3 存储桶传递到 StepFunctions 状态机?
- google-sheets - 创建未使用表格签到的列表?
- typescript - 是否存在表示具有任何属性但不是数组的对象的类型
- grails - Geb-Spock 使用了错误的 Groovy 版本
- kubernetes - 在 helm 图表上运行 helm install 命令时未创建 pod 模板文件
- epplus - 如何使用 EPPlus 插入大写 yat 符号
- c# - 从 C# 运行 R 脚本
- javascript - ExpressJS:身份验证时,我是从后端存储 JWT 令牌还是从前端存储 JWT 令牌?
- azure - 使用 Microsoft Teams 获取机器人的访问令牌以与图形 API 一起使用