SQL查询多对多关系

时间:2018-08-07 09:38:43

标签: mysql sql postgresql

我有很多关系

  table:  images    
  id  imageName  
   1    pic01
   2    pic02
   3    pic03    

  table:  imagesKeywords
  imageId  keywordId
   1        2
   1        3
   1        4
   2        3
   3        1
   3        4
   3        2

  table:  keywords
  id  keywordName  
   1    car
   2    tree
   3    cat
   4    phone

每个图像都有一些关键字,不同的图像可以具有相同的关键字。

我需要搜索图像,它们具有特定的keywordName

示例1:搜索汽车电话

结果应为: pic03

示例2:搜索电话

结果应为: pic01 pic03

3 个答案:

答案 0 :(得分:3)

您似乎想要JOINGROUP BY条款:

select i.imageName
from images i inner join
     imagesKeywords ik 
     on ik.imageId = i.id inner join 
     keywords k
     on k.id = ik.keywordId 
where k.keywordName in ('car', 'phone')
group by i.imageName
having count(*) = 2; 

答案 1 :(得分:0)

据我了解,这应该有效:

select i.imageName as name from keywords k
join imagesKeywords iK on k.id = iK.keywordId
join images i on iK.imageId = i.id
group by i.imageName;

答案 2 :(得分:0)

一种可能的解决方案,

with subquery as
       (select i1.imageName, k1.keywordName from keywords k1 join imagekeywords ik1 on k1.id=ik1.keywordId join images i1 on i1.id = ik1.imageId )    
 select a.imageName from subquery a join subquery b on a.imageName=b.imageName where a.keywordName ='car' and b.keywordName='phone';