0

I have a products database, and this is how I'm running a query to show results for the keywords 'chair':

SELECT `products`.product_id, products.product_name
FROM (`products`)
WHERE  `product_name`  LIKE '%chair%'
AND `products`.`active` =  1

 UNION ALL

SELECT `products`.product_id, products.product_name
FROM (`products`)
WHERE  `category_id` IN (128,135,136,138)
AND `products`.`active` =  1

I saw on this thread: MySQL order by "best match" how to order by 'best match' given only a %like% constraint.

How can I implement something similar on my particular query?

Community
  • 1
  • 1
Zaki Aziz
  • 3,592
  • 11
  • 43
  • 61

1 Answers1

1

If I don't misunderstand what you are after, you can try to put ordering statement at the end. And put brackets around each select statement to prevent MySQL from wrongly applying ORDER BY to result of the second SELECT statement instead of entire UNION ALL result :

(SELECT `products`.product_id, products.product_name
FROM (`products`)
WHERE  `product_name`  LIKE '%chair%'
AND `products`.`active` =  1)

 UNION ALL

(SELECT `products`.product_id, products.product_name
FROM (`products`)
WHERE  `category_id` IN (128,135,136,138)
AND `products`.`active` =  1)

ORDER BY
  CASE
    WHEN `product_name` LIKE 'chair%' THEN 1
    WHEN `product_name` LIKE '%chair' THEN 3
    ELSE 2
  END
har07
  • 88,338
  • 12
  • 84
  • 137