traxwriter
traxwriter

Reputation: 55

mysql query order by exact match with multiple LIKE clauses

OK, i've been working with this for some time and I'm a little stuck.

Maybe I'm going about it all wrong!

Basically I have a query for a search field. The general idea is to select result based on LIKE %% whilst still putting exact matches first.

So for example if you search 47 I want everything with 47 in either id, surname, or company_name to show, however the result with id number 47 should be on top and the same if I typed a surname.

Please see my code below, it may help to clarify my question.

SELECT id, 
IF(company_name IS NOT NULL AND company_name <> '', company_name, surname) AS name, 
first_name, country, phone1, isowner, isholidayrenter, isproholidayrenter, 
islongtermrenter, isprolongtermrenter, isprobuyer, isbuyer 
FROM clients 
WHERE id LIKE '$search' OR surname LIKE '$search' OR company_name LIKE '$search'
union all
SELECT id, 
IF(company_name IS NOT NULL AND company_name <> '', company_name, surname) AS name,      
first_name, country, phone1, isowner, isholidayrenter, isproholidayrenter,     
islongtermrenter, isprolongtermrenter, isprobuyer, isbuyer 
FROM clients 
WHERE id LIKE '%$search%' AND id NOT LIKE '$search' OR surname LIKE '%$search%' 
and SURNAME NOT LIKE '$search' OR company_name LIKE '%$search%' 
and company_name NOT LIKE '$search' 
LIMIT $start, $limit";

`

Upvotes: 2

Views: 1704

Answers (1)

Ravinder Reddy
Ravinder Reddy

Reputation: 24002

Try this:

(select exact match) union all with (select partial match omitting exact match)

Example:

(
  SELECT
      id, 
      IF( company_name IS NOT NULL AND company_name <> '', company_name, surname ) AS name,
      first_name, country, phone1, isowner, isholidayrenter, isproholidayrenter, 
      islongtermrenter, isprolongtermrenter, isprobuyer, isbuyer 
  FROM
      clients 
  WHERE
      id LIKE '$search' OR 
      surname LIKE '$search' OR 
      company_name LIKE '$search'
)
union all
(
  SELECT 
      id,
      IF( company_name IS NOT NULL AND company_name <> '', company_name, surname ) AS name, 
      first_name, country, phone1, isowner, isholidayrenter, isproholidayrenter,
      islongtermrenter, isprolongtermrenter, isprobuyer, isbuyer 
  FROM
      clients 
  WHERE
      ( id LIKE '%$search%' AND id NOT LIKE '$search' ) OR 
      ( surname LIKE '%$search%' AND SURNAME NOT LIKE '$search' ) OR
      ( company_name LIKE '%$search%' AND company_name NOT LIKE '$search' )
)
LIMIT $start, $limit;

Upvotes: 5

Related Questions