Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 423
jerrymouse Avatar asked Oct 13 '11 10:10

jerrymouse


1 Answers

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.

like image 61
jerrymouse Avatar answered Nov 05 '22 13:11

jerrymouse