得到一個更好的索引
通過對前綴直接訂貨,而不是長度(前綴):
SELECT dialstring FROM call_routing
WHERE number like prefix || '%'
ORDER BY prefix DESC
LIMIT 1
爲什麼?
因爲數字abcdef
的選定行將作爲前綴。所以會像數字:
一個 AB ABC ABCD
所以,如果你命令他們按字母順序它足以得到最長的列表,以最短,這就是你想要的。
您也可以得到使用更強的過濾器:
prefix between 'a' and 'abcde'
。所有的前綴將按字母順序排列,最短的前綴爲>=
,最長的字母順序爲<=
。
因此,可以表示爲:
SELECT dialstring FROM call_routing WHERE
prefix between substr(number, 1, 1) and number -- range filter (use index)
AND number like prefix || '%' -- only relevant data (normal filter)
ORDER BY prefix DESC -- index will work
LIMIT 1
當然和索引將在列前綴。
Cache all?
是的,請。 :)
你有多少物品?如果它不是一個巨大的列表,請將其加載到內存中。
然後你可以有一個TreeMap(如果你想要通過前綴命令)或一個HashMap(如果你希望首先找到最長的前綴,並繼續嘗試每次少用一個字符)。哪一個會更好?取決於a >> abcde
範圍內的前綴數量,並且不符合like
條件(例如,abbde
)。
如果沒有很多條目
你可以使用一個數組,由前綴降序排序:
be
b
abcde
abbbc
abd
ab
爲了找到好前綴做一個Arrays.binarySearch(T[], T key, Comparator<T>)
找到,如果你的手機是在那裏(abcde
)。如果是...好的。如果不是你前進,直到:
- you find a prefix (OK, this is the winner)
- it doesn't start with the same char (there are no prefix)
這樣,你是在橫穿整個範圍abcde >> a
,尋找第一個前綴(它是最長的可能)。
好一個
正在爲T-R-E-E(我不知道這個名字)。製作一棵樹,每個節點只包含一個字母(在你的情況下是數字)。
0 // represents 0
->
2 // represents 02
-> 1 // represents 021
-> 3 // represents 023
->
4 // represents 04
所以,當你爲你最長前綴您嘗試獲取儘可能深地在你的樹:
Node n = root;
for (char c: number) {
if ((child = n.hasChild(c)) != null)
{
prefix += c;
n = child;
}
else
break;
}
你只需要一個創建
class Node
{
int digit;
Map<Integer, Node> childs = new HashMap<Integer, Node>(); // or a 10 bucket array :)
YourInfo info;
}
而對於創建結構:
findOrCreateNode(prefix).setInfo(info);
其中findOrCreateNode與之前相同,但是當它未找到該節點時...創建它(n.put(c, new Node(c))
)。
數據庫只包含2位或4位前綴號碼?或者更多,更少? – chris
前綴可以從2到7位數 – markus