Many to Many SQL Query for selecting all Images Tagged with certain words

泪湿孤枕 提交于 2019-12-06 06:49:53

问题


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?


回答1:


Here's the working query I wrote:

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)

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.




回答2:


You'd join images to tags_image_relations, then tags_image_relations to tags, then filter WHERE the name field is IN a list of tag names desired. It's the simplest, most obvious, and cleanest?



来源:https://stackoverflow.com/questions/7752620/many-to-many-sql-query-for-selecting-all-images-tagged-with-certain-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!