Home » Php » php – Select and order by most matches

php – Select and order by most matches

Posted by: admin July 12, 2020 Leave a comment

Questions:

Let’s say I explode a string passed in a search. Example: “if there was a dog” “if there were a dog” (silly American).

We explode based on ” ” so results…

if
there
were
a
dog

Now I want to run a SQL select * from table_name query where column_name like
'%something%' or column_name like '%somethingelse%'...

I’m trying to determine how I can search a table and order by rows that contain the most matches. (ie, if row 45 contained 4 of the above split items and row 21 only contained 2, row 45 should be displayed at top in the results).

This would be a primitive “search relevance” logic. Is there a specific term for this kind of retrieval in SQL?

Suggestions?

How to&Answers:

Just put the comparisons in the order by clause, use case statements to convert them to 0/1, and add them up:

select *
from table_name query
where column_name like '%something%' or column_name like '%somethingelse%'
order by ((case when column_name like '%something%' then 1 else 0 end) +
          (case when column_name like '%somethingelse%' then 1 else 0 end)
          . . .
         ) desc

I would be inclined to write the query as:

select (Match1+Match2+. . .) as NumMatches, <rest of columns>
from (select t.*,
             (case when column_name like '%something%' then 1 else 0 end) as Match1,
             . . .
      from tablename
     ) t
order by NumMatches desc

Answer:

Here’s a variation of @Gordon’s excellent answer:

SELECT FieldToSearch, 
  CASE WHEN ' ' + FieldToSearch + ' ' like '% if %' then 1 else 0 end
      + CASE WHEN ' ' + FieldToSearch + ' ' like '% there %' then 1 else 0 end 
      + CASE WHEN ' ' + FieldToSearch + ' ' like '% was %' then 1 else 0 end
      + CASE WHEN ' ' + FieldToSearch + ' ' like '% a %' then 1 else 0 end
      + CASE WHEN ' ' + FieldToSearch + ' ' like '% dog %' then 1 else 0 end matches
FROM YourTable
ORDER BY matches DESC

And here is the Fiddle.

Best of luck!