Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to weight 'ORDER BY' in mysql?

I have a full text query that ends with:

 ORDER BY RELEVANCE DESC, CLICK_RATE DESC

Can I give weight to the columns in the order by? Maybe 0.3 to relevance and 0.7 to click_rate?

As things are right now, even if I switch them around, the results are not satisfactory.

As an alternative how can have the top 3 results sorted by CLICK RATE and the rest sorted by relevance.

like image 462
califmerchant Avatar asked Apr 23 '12 19:04

califmerchant


People also ask

How do I arrange in ascending order in MySQL?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Can we use order by before group by in MySQL?

This is not permitted if the ONLY_FULL_GROUP_BY SQL_MODE is used." So you can't guarantee the order. You however use a function such as MAX(info) to get a specific value.

How do I sort a list in MySQL?

Summary. Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order. The ORDER BY clause is evaluated after the FROM and SELECT clauses.


1 Answers

This should work

ORDER BY (.3 * RELEVANCE) + (.7 * CLICK_RATE) DESC

DEMO

Update from comments

to make top 3 results sort by click_rate, and the rest sort by relevance

You'd need to first identify the first 3 using a subquery and do the ordering

SELECT test.id, 
       test.relevance, 
       test.click_rate, 
       top_3_click_rate.id         t3_id, 
       top_3_click_rate.click_rate t3_click_rate 
FROM   test 
       LEFT JOIN (SELECT id, 
                         click_rate 
                  FROM   test 
                  ORDER  BY click_rate DESC 
                  LIMIT  3) top_3_click_rate 
         ON test.id = top_3_click_rate.id 
ORDER  BY top_3_click_rate.click_rate DESC, 
          test.relevance DESC 

DEMO

like image 183
Conrad Frix Avatar answered Sep 21 '22 15:09

Conrad Frix