2010-04-21 21 views
1

我正在寫sql來通過一些參數來搜索數據庫。我將如何去訂購與where子句中的大部分參數匹配的項目的結果集。例如:如何按照sql語句的where子句中的匹配參數數量來排序表?

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 

應命令等:

2,3,1

感謝。 (PS查詢不是那麼容易,有很多加入的,並在那裏有很多OR年代)

埃坦

+0

什麼數據庫? – 2010-04-21 08:52:48

回答

5

如果MySQL:

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

如果PostgreSQL的:

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

如果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 
+0

我不知道你可以這樣做。好吧,我今天學過的其他東西。 – 2010-04-21 09:03:28

+0

我認爲OP仍然希望擁有'WHERE用戶名='eitan'OR email ='[email protected]'OR company ='eitan'' clause – 2010-04-21 11:49:41

+0

是的,我知道,但那是最好的可以完成的,他只需要添加WHERE子句。 afaik,還沒有構造可以衡量WHERE子句的真實性 – 2010-04-21 13:37:40