php - organizing search results based on longest match -
i have database table contains project keywords. each project has several keywords.
in web application, user can perform search entering multiple keywords search for. if user enters (for example) 4 keywords, want return search result list of projects. projects should ordered based on longest matches first. first projects listed ones matched on 4 keywords, followed projects matched on 3 out of 4 keywords, etc.
what query can write return results?
this rough idea of think query like:
select projectid project_keyword keyword = '*keyword1*' or keyword = '*keyword2*' or keyword = '*keyword3*'
but want projectid
matches 3 keywords displayed first (if any), followed projectid
matched 2 out of 3 keywords, etc. projectid
don't have matching keywords not returned.
example:
projectid keyword --------- ------- 456 salsa 456 guacamole 456 tamale 511 salsa 511 tamale 511 burrito 511 taco 654 margarita 654 nachos 789 margarita 789 salsa 789 taco
for user keyword search 'salsa','tamale','burrito', query should return these projectid, in order.
projectid --------- 511 (matches three) 456 (matches two) 789 (matches one)
how rows query returned in specified order? (what query can write that.)
something should work:
select k.projectid project_keyword k k.keyword in ('*keyword1*','*keyword2*','*keyword3*') group k.projectid order count(distinct k.keyword) desc, k.projectid
(this assumes table contains multiple rows projectid, 1 row each keyword. if that's not how table organized, if it's single row, , looking matching keywords occur somewhere in column, we'd need different query.)
if want return list of keywords matched, use group_concat
aggregate in select list
select k.projectid , group_concat(distinct k.keyword order k.keyword) keywords_matched ...
Comments
Post a Comment