mysql - 多对多关系的SQL查询

标签 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:搜索 treephone

结果应该是:pic01, pic03

最佳答案

您似乎想要使用 GROUP BY 子句的 JOIN :

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; 

关于mysql - 多对多关系的SQL查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51723573/

相关文章:

MySQL查找按时间分割的出勤学生人数

mysql - MySQL 中的 "Cannot add foreign key constraint"错误

Postgresql regexp_replace() 反斜杠和双引号

sql - 循环遍历模式中的表

php - mysql 按另一列计算不同的行并对结果进行分组

mysql - 获取mysql中上个月的日期

对两列集合的 SQL 检查约束

python - 如何进行 Django 子查询

php - 无法回显 laravel 'created_at' 时间戳值,而是显示 1970 年 1 月 1 日

sql - 多个不明显