SQL:选择 * 其中属性与数组中的所有项目匹配
在 Rails 应用程序中工作,我有以下表结构(仅相关列)
照片(id:整数) 标签(photo_id:整数,tag_id:整数) 标签(id:整数,名称:字符串)
我有以下 SQL 查询:
SELECT distinct photos.*
FROM \"photos\" INNER JOIN \"taggings\" ON \"photos\".\"id\" = \"taggings\".\"photo_id\"
INNER JOIN \"tags\" ON \"tags\".\"id\" = \"taggings\".\"tag_id\"
WHERE \"tags\".\"name\" IN ('foo', 'bar')
当我生成此查询时,我传递一个标签数组(在本例中为 ["foo","bar"]
)。该查询正确搜索与数组中传递的任何标签匹配的照片。
如何更改此查询以选择具有所有给定标签的记录(即照片仅在标有“foo”和“bar”时才匹配,而不是选择具有任何给定标签的记录?
Working in a Rails App, I have the following table structure (pertinent columns only)
Photos (id: integer)
Taggings (photo_id: integer, tag_id: integer)
Tags (id: integer, name:string)
I have the following SQL query:
SELECT distinct photos.*
FROM \"photos\" INNER JOIN \"taggings\" ON \"photos\".\"id\" = \"taggings\".\"photo_id\"
INNER JOIN \"tags\" ON \"tags\".\"id\" = \"taggings\".\"tag_id\"
WHERE \"tags\".\"name\" IN ('foo', 'bar')
When I generate this query I'm passing in an array of tags (in this case ["foo","bar"]
). The query correctly searches for photos that match ANY of the tags passed in the array.
How can I change this query to select records with ALL of the given tags (ie a photo only matches if tagged with "foo" AND "bar", instead of selecting records with ANY of the given tags?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能有更好的方法,但这应该可以
There may be a better way, but this should do it
如果您在 Rails 中,则不需要查询来执行此操作。
Tags.find(1).taggings
应该为您提供带有该标签的所有照片的数组,您可以类似地迭代所有标签,并收集数组,然后对您获得的数组执行类似的操作。
基本上是“与”数组并获得独特的照片。这样您就可以获得与所有标签匹配的照片。
If you are in rails you don't need query to do this.
Tags.find(1).taggings
should give you an array of all photos with that tagyou can similarly iterate over all tags, and collect the arrays and then just do something like on the arrays you have got.
Basically 'and' the arrays and get the unique photos.This way you can get the photos that match all the tags.