views:

23

answers:

2

I am working on a search query in PostgreSQL, and one of the things I do is sort my query results by the number of parameters matched. I have no clue how this can be done. Does anyone have a suggestion or solution?

 Table
 brand     color     type     engine
 Ford      Blue      4-door   V8
 Maserati  Blue      2-door   V12
 Saturn    Green     4-door   V8
 GM        Yellow    1-door   V4

 Current Query
 SELECT brand FROM table WHERE color = 'Blue' or type = '4-door' or engine = 'V8'

 Result Should Be
 Ford      (3 match)
 Saturn    (2 match)
 Maserati  (1 match)
A: 

For Mysql it would look like this,

SELECT brand, 
IF(color = 'Blue',1,0)+IF(type = '4-door', 1,0)+IF(engine = 'V8',1,0) 
   AS num_matches
FROM table WHERE color = 'Blue' or type = '4-door' or engine = 'V8'

Double check IF syntax for PostgreSQL. You can also use CASE.

a1ex07
And add 'SORT BY 2 Desc', to give the correct sorting order.
inflagranti
+2  A: 

I think you should be able to do:

ORDER BY
    CASE WHEN color = 'Blue' THEN 1 ELSE 0 END +
    CASE WHEN type = '4-door' THEN 1 ELSE 0 END +
    CASE WHEN engine = 'V8' THEN 1 ELSE 0 END DESC
Tom H.
@Tom H Works perfectly. Thanks!
Ben Dauphinee