I am implementing a tag based searching where user can insert multiple tags to search for specific entity. One entity can have as many tags. But its not necessary to have all the tags user searched for to be listed in the results.
For example, where user enters three tags, say, “Shoes”,”leather”,”formal”, every entity having one or more of these tags can be in the list.
I am using union to return a full list of entities having any one of these keywords, but the problem is that I want them sorted according to the number of tags found in a category.
For example, entities having all three tags, “Shoes”,”leather”,”formal”, should come above then entities having only one or two of them. Is there any sql functionality to perform this kind of searching?
[EDIT]
My table layout is:
Entity table
- Entity_name
- Entity_id(auto inc primary key)
Tags table
- Tag
- Entity_id
Am unable to solve my purpose. Using this query right now:
select entity.entity_name from entity.entity_id join tags on tags.entity_id=entity.entity_id where tags.tag="first tag"
union
select entity.entity_name from entity.entity_id join tags on tags.entity_id=entity.entity_id where tags.tag="second tag"
union
select entity.entity_name from entity.entity_id join tags on tags.entity_id=entity.entity_id where tags.tag="third tag"
As I told, this is not solving my purpose.
This should do it for you:
It counts the matched tags by entity, then sorts them with the highest match first.
Note also that boolean style fulltext matching will provide functionality like this.