我在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'和'google'标记的图像的relative_url”的查询
对此最优化的查询有哪些?
答案 0 :(得分:3)
这是我写的工作查询:
SELECT i.id, i.relative_url, count(*) as number_of_tags_matched
FROM images i
join tags_image_relations ti on i.id = ti.image_id
join tags t on t.id = ti.tag_id
where t.name in ('google','microsoft','apple')
group by i.id having count(i.id) <= 3
order by count(i.id)
此查询将首先显示与所有三个标签匹配的图像,然后匹配3个标签中至少2个的图像,最后至少1个标签。
答案 1 :(得分:0)
您将images
加入tags_image_relations
,然后tags_image_relations
加入tags
,然后过滤WHERE
name
字段为{{1}所需的标记名称列表。这是最简单,最明显,最干净的吗?