gpt4 book ai didi

关联表上多行的MySQL过滤器

转载 作者:行者123 更新时间:2023-11-28 23:53:52 25 4
gpt4 key购买 nike

使用 MySQL,是否有一种有效的方法来通过检查关联表上是否存在多行来过滤一个表上的记录?

例如,我有一个图像表和另一个识别该图像中对象的表:

 table: images

id | url
----+--------------------------------
1 | http://www.example.com/foo.png
2 | http://www.example.com/bar.png
3 | http://www.example.com/baz.png


table: image_tags

image_id | tag
----------+-------------
1 | cats
1 | living-room
2 | beach
2 | towel
2 | dogs
3 | cats
3 | dogs
3 | goldfish

如果我想查询包含 catsdogs 的所有图像,最好的方法是什么?如果我想要包含 catsdogsgoldfish 的图像怎么办?

我尝试过的一种方法是先查询包含狗的图像的所有 image_id,然后再查询包含猫的图像,然后取交集。我可以在我的应用程序中执行此操作,但我想知道是否有一种方法可以使用 SQL 处理任意数量的标签来运行相同的操作。

最佳答案

我喜欢使用 group byhaving 来处理这些类型的查询(“set-within-set”查询):

select it.image_id
from image_tags it
where it.tag in ('cats', 'dogs')
group by it.image_id
having count(*) = 2;

请注意,“2”需要等于您希望在 in 列表中匹配的标签数。

关于关联表上多行的MySQL过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32127152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com