views:

32

answers:

1

I'm writing sql to search a database by a number of parameters. How would I go about ordering the result set by the items that match the most parameters in the where clause. For example:

SELECT * 
FROM users 
WHERE username = 'eitan' 
OR email = '[email protected]' 
OR company = 'eitan'


Username   |  email                |   company

1) eitan   |     [email protected]     |     blah

2) eitan   |     [email protected]   |    eitan

3) eitan   |    [email protected]    |     blah

should be ordered like:

2, 3, 1.

Thanks. (ps the query isn't that easy, has a lot of joins and a lot of OR's in the WHERE)

Eitan

+3  A: 

If MySQL:

SELECT * FROM users 
ORDER BY 
    (username = 'eitan') 
    + (email = '[email protected]') 
    + (company = 'eitan') 
    DESC

If PostgreSQL:

SELECT * FROM users 
ORDER BY 
    (username = 'eitan')::int 
    + (email = '[email protected]')::int 
    + (company = 'eitan')::int 
    DESC

If Sql Server:

SELECT * FROM users 
ORDER BY 
    case when username = 'eitan' then 1 else 0 end
    + case when email = '[email protected]' then 1 else 0 end
    + case when company = 'eitan' then 1 else 0 end
    DESC
Michael Buen
I had no idea you could do that. Well, something else I've learnt today.
Joel Goodwin
I think the OP would still like to have the `WHERE username = 'eitan' OR email = '[email protected]' OR company = 'eitan'` clause
KM
yeah i know, but that's the best that could be done, he just need to add that WHERE clause. afaik, there's no construct yet that can weigh the truthiness of WHERE clause
Michael Buen
You can still add the WHERE clause can't you with the ORDER BY can;t you?
Eitan
yeah must be added. but to minimize the noise in the code, i only show the proof-of-concept code for doing math on booleans, everything else is corollary
Michael Buen
ok it works thanks :-)
Eitan