我正在为包含某些媒体文件的压缩文件创建数据库。要连接每个.zip中的文件,我使用中间表compressed_has_medium
。
数据库
medium compressed_has_medium compressed
id | filename id | medium_id | compressed_id id | filename
-------------- ------------------------------ -------------
1 | file1.mp3 1 | 1 | 1 1 | compressed1.zip
2 | file2.mp3 1 | 2 | 1 2 | compressed2.zip
3 | file3.mp3 1 | 3 | 1 3 | compressed3.zip
4 | file4.mp3 1 | 4 | 1
5 | file5.mp3 1 | 5 | 1
6 | file6.mp3 1 | 6 | 1
7 | file7.mp3 1 | 1 | 2
8 | file8.mp3 1 | 2 | 2
9 | file9.mp3 1 | 3 | 2
问题
我需要返回包含我发送给MySQL的ID的每个.zip。 如果zip1有文件1,2,3,4,5,6并且我想要文件3,4的zip,它应该返回zip1。 但是如果zip2有文件1,2,3并且我请求文件3,4,则不应该返回。
部分解决方案
我已经尝试了很多并且得到了这个解决方案:http://sqlfiddle.com/#!9/cb0864/37但这是一个非常丑陋的查询,可能效率不高。
SELECT c.*, GROUP_CONCAT(cm.medium_id) as media
FROM compressed as c
INNER JOIN compressed_has_medium as cm
ON cm.compressed_id = c.id
GROUP BY cm.compressed_id
HAVING (media LIKE '%,3,%' OR media LIKE '3,%' OR media LIKE '%3')
AND (media LIKE '%,4,%' OR media LIKE '4,%' OR media LIKE '%,4')
你知道更好的方法吗?
许多坦克!
答案 0 :(得分:1)
可能这是你所期待的我相信
我已经改变了你的小提琴中的查询:http://sqlfiddle.com/#!9/cb0864/62
SELECT c.*,GROUP_CONCAT(cm.medium_id) as media
FROM compressed as c
LEFT JOIN compressed_has_medium as cm
ON cm.compressed_id = c.id
WHERE cm.medium_id in (3,4)
GROUP BY cm.compressed_id
having sum(cm.medium_id in (3,4)) = 2 and // 2 represents the numbers of medium id you are entering
sum(cm.medium_id not in (3,4)) = 0