多对多 SQL 查询,用于选择用某些单词标记的所有图像
我在 Postgres 中有 2 个表:
CREATE TABLE "images" (
"id" serial NOT NULL PRIMARY KEY,
"title" varchar(300) NOT NULL,
"relative_url" varchar(500) NOT NULL)
为了
CREATE TABLE "tags" (
"id" serial NOT NULL PRIMARY KEY,
"name" varchar(50) NOT NULL)
在图像和标签之间建立多对多关系,我还有另一个表:
CREATE TABLE "tags_image_relations" (
"id" serial NOT NULL PRIMARY KEY,
"tag_id" integer NOT NULL REFERENCES "tags" ("id") DEFERRABLE INITIALLY DEFERRED,
"image_id" integer NOT NULL REFERENCES "images" ("id") DEFERRABLE INITIALLY DEFERRED)
现在我必须编写一个查询,例如“选择标有‘apple’和‘microsoft’的所有图像的relative_url和'google'“
对此最优化的查询是什么?
I have 2 Tables in Postgres:
CREATE TABLE "images" (
"id" serial NOT NULL PRIMARY KEY,
"title" varchar(300) NOT NULL,
"relative_url" varchar(500) NOT NULL)
and
CREATE TABLE "tags" (
"id" serial NOT NULL PRIMARY KEY,
"name" varchar(50) NOT NULL)
To establish many to many relationship between images and tags I have another table as:
CREATE TABLE "tags_image_relations" (
"id" serial NOT NULL PRIMARY KEY,
"tag_id" integer NOT NULL REFERENCES "tags" ("id") DEFERRABLE INITIALLY DEFERRED,
"image_id" integer NOT NULL REFERENCES "images" ("id") DEFERRABLE INITIALLY DEFERRED)
Now I have to write a query like "select relative_url of all images tagged with 'apple' and 'microsoft' and 'google' "
What can the most optimized query for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是我编写的工作查询:
该查询将首先显示与所有三个标签匹配的图像,然后显示与 3 个标签中至少 2 个标签匹配的图像,最后至少显示 1 个标签。
Here's the working query I wrote:
This query will first show the images matching all three tags, then the images matching at least 2 of the 3 tags, finally at least 1 tag.
您可以将
images
加入tags_image_relations
,然后将tags_image_relations
加入tags
,然后过滤WHERE
name
字段是IN
所需标签名称的列表。它是最简单、最明显、最干净的吗?You'd join
images
totags_image_relations
, thentags_image_relations
totags
, then filterWHERE
thename
field isIN
a list of tag names desired. It's the simplest, most obvious, and cleanest?