List:General Discussion« Previous MessageNext Message »
From:Roger Baklund Date:May 9 2005 10:12pm
Subject:Re: Sorting by relevance?
View as plain text  
Erik Bukakis wrote:
> I just learned a lot stuff at 
> http://dev.mysql.com/doc/mysql/en/sorting-rows.html including sorting by 
> number-to-text, text-to-number, names, specific values, etc.
> 
> However, the document didn't mention on how to sort by relevance.
> 
> For instance, someone search for "Ang":
> COLUMN NAME: name
> COLUMN TYPE: varchar (255)
> DATA:
> John Ang
> La Chi Zoygote
> Anglosaxon
> Marco Polo
> Ang Fernandez
> John Pang Cuyi
> 
> Query result should be:
> Ang Fernandez
> John Ang
> Anglosaxon
> John Pang Cuyi
> 
> Is it possible to sort a column this way?

"This way" and only four rows in the example is a bit vague, but maybe 
something like this could work for you:

$crit = 'Ang'; # test case

SELECT name
   FROM t1
   WHERE name like '%crit%'
   ORDER BY
     name != '$crit',          # exact match
     name not like '$crit %',  # first word
     name not like '% $crit',  # last word
     name not like '$crit%',   # start of first word
     name not like '% $crit%', # start of non-first word
     name                      # alphabetically

Some of these are not in your example, I was just guessing... but you 
get the idea. Each expression in the ORDER BY clause returns 0 (false) 
or 1 (true). Because 0 is smaller than 1, and ASC is the default sorting 
order, we want each expression to be FALSE, so that it is sorted first. 
That's why I negated all expressions. An alternative would be to use 
DESC after each expression.

-- 
Roger

Thread
Sorting by relevance?Erik Bukakis9 May
  • Re: Sorting by relevance?Rhino9 May
    • Re: Sorting by relevance?Michael Stassen9 May
  • Re: Sorting by relevance?Eamon Daly9 May
  • Re: Sorting by relevance?Roger Baklund10 May
    • Re: Sorting by relevance? [SOLVED]Erik10 May
      • character set in MySQL 4.1Chenzhou Cui11 Jul
        • Re: character set in MySQL 4.1Gleb Paharenko11 Jul