There is my entity table and tags bound to it through another table (many-to-many relation).
I have an entity selected and my goal is to find a set of entities which have as much similar tags with it as possible. This set must be ordered by 'similarity' – amount of tags each entity shares with chosen entity. Tags are similar if they have the same ids.
I'm wondering if there's elegant and fast way to do that with single query.
The only solution I see now is to fetch all the tag-entity relations and compute their similarity in my application, and then make another database query to select what i've computed, but it doesn't look very graceful.
Database structure:
entity id ...
tag id name
entity_tag entity_id tag_id
Update: final solution for MySQL.
So I have tables for paintings, tags and painting_tag relation. This query fetches similar paintings and their 'similarity index' for previously selected painting.
SELECT site_painting.*, Count(tr.tag_id) as similarity
From site_painting_tag_relation as tr
Inner Join site_painting_tag_relation as tr2 ON ( tr2.tag_id = tr.tag_id and tr2.painting_id = :id )
Left join site_painting on site_painting.id=tr.painting_id
Where tr.painting_id <> :id
Group By tr.painting_id
Having Count(*) > 0
Order By Count(*) DESC, tr.painting_id limit 1