業務需要,通過lucene查出符合搜索條件的id,然后在詳情表里查出這些id的詳情
1
|
SELECT
id,QUESTION,QUESTIONCOMMENT
FROM
"ASKDBA_QUESTION"
where
ID
IN
(63,62,65,61,64);
|
其中id是根據搜索的權值進行的排序,sql沒有問題,但是通過這種sql查出來的結果的排序就不對了。
1
2
3
4
5
|
<b>61 測試問題101 測試問題101
62 測試問題102 測試問題102
63 測試問題103 測試問題103
64 測試問題104 測試問題104
65 測試問題106 測試問題106 <
/b
>
|
這個一般默認是按照主鍵來排序的,而並不是根據in中條件的順序來排列的
網上有個案例是按照in順序來排序的解決方案,是利用sql server的charindex來解決的。不過僅限於sqlserver
1
2
3
|
<b>
select
id,title
from
info
where
id
in
(
'3,1,2,5,4'
)
order
by
charindex(
','
+
convert
(
varchar
,ID)+
','
,
',3,1,2,5,4,'
) </b>
|
http://www.sosuo8.com/article/show.asp?id=2958
CHARINDEX函數返回字符或者字符串在另一個字符串中的起始位置。CHARINDEX函數調用方法如下: CHARINDEX ( expression1 , expression2 [ , start_location ] ) Expression1是要到expression2中尋找的字符中,start_location是CHARINDEX函數開始在expression2中找expression1的位置。 CHARINDEX函數返回一個整數,返回的整數是要找的字符串在被找的字符串中的位置。假如CHARINDEX沒有找到要找的字符串,那么函數整數“0”
這里有小技巧,可以利用charindex來進行模糊匹配
1
2
|
select
name
,pass
from
dps_user
where
charindex(
'張三'
,dps_user.
name
)> 0
|
但是oracle下是怎么實現相同的效果的呢?可以使用decode函數
1
|
SELECT
id,QUESTION,QUESTIONCOMMENT
FROM
"ASKDBA_QUESTION"
where
ID
IN
(63,62,65,61,64)
ORDER
BY
"DECODE"
(id, 63,1,62,2,65,3,61,64);
|
1
2
3
4
5
|
63 測試問題103 測試問題103
62 測試問題102 測試問題102
65 測試問題106 測試問題106
61 測試問題101 測試問題101
64 測試問題104 測試問題104
|
結果是符合條件的
decode函數是oracle很強大的一個函數,
可以參考一下這個文檔
http://www.cnblogs.com/ZHF/archive/2008/09/12/1289619.html
http://database.ctocio.com.cn/tips/489/6064989.shtml
mysql里是怎么實現這種需求的呢?
其實很簡單orderby filed(col,1,2,3,4...)就行
1
|
SELECT
*
from
city
where
id
in
(4,2,3,1)
ORDER
BY
field(id,4,2,3,1)
|
1
2
3
4
|
4 Mazar-e-Sharif AFG Balkh 127800
2 Qandahar AFG Qandahar 237500
3 Herat AFG Herat 186800
1 Kabul AFG Kabol 1780000
|
其中filed這個函數的用法如下:
FIELD(str,str1,str2,str3,…) Returns the index (position) of str in the str1, str2, str3, … list. Returns 0 if str is not found. 排序過程:把選出的記錄的 id 在 FIELD 列表中進行查找,並返回位置,以位置作為排序依據。 這樣的用法,會導致 Using filesort,是效率很低的排序方式。除非數據變化頻率很低,或者有長時間的緩存,否則不建議用這樣的方式排序。
另外也可以使用substring_index函數或者find_inset函數
http://kidcraze.org/mysql-in-%E6%8E%92%E5%BA%8F%E9%97%AE%E9%A2%98/
總結一下,sql查詢一般會按照orderby字段來進行排序,如果沒有order by 字段,默認是按照數據存儲的順序來顯示的。
所以如果保證按照in順序的字段來排序輸出的話,可以參考以上幾種方法,即sqlserver借助charindex,oracle借助decode,mysql借助orderby field。