Mysql SQL多对多关系查询

Mysql SQL多对多关系查询,mysql,sql,postgresql,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:

我有很多对很多的关系

  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
每个图像都有一些关键字,不同的图像可以有相同的关键字

我需要搜索图像,它们有一个特定的
关键字名称

示例1:搜索汽车手机

结果应该是:pic03

示例2:搜索电话


结果应该是:pic01pic03

您似乎想要
加入
分组依据
子句:

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; 

您似乎希望
加入
分组依据
子句:

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; 

据我所知,这应该是可行的:

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;

据我所知,这应该是可行的:

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;
一个可能的解决办法

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';
一个可能的解决办法

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';