我想获得与select2中的邮政编码最接近的匹配。如果用户键入DE2,但如果用户尝试输入其余的邮政编码,那么说DE20BE,'BE'将不会显示(当前设置的限制为4)但是它可以与最接近DE20的匹配所以说DE2,目前它回来时没有结果,下面的代码,我想我不需要允许空格?:
这是我的MySQL查询:
SELECT `postcode` FROM `postcodes` WHERE `postcode` LIKE '%?%' ORDER BY `postcode` LIMIT 0,50;
这里是JSON结果:
[{"ok":1,"text":"DE1"},{"ok":1,"text":"DE11"},{"ok":1,"text":"DE12"},{"ok":1,"text":"DE13"},{"ok":1,"text":"DE14"},{"ok":1,"text":"DE15"}]
这是JS:
var item = [];
function postCodeAjaxAutoComplete(element, url) {
$(element).select2({
placeholder: "Select a Postcode Area (E10)",
minimumInputLength: 1,
maximumInputLength: 4,
multiple: false,
id: function(e) { return e.text; },
ajax: {
url: url,
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
},
formatResult: formatResult,
formatSelection: formatSelection,
initSelection: function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
data.push({
text: item[0]
});
});
callback(data);
}
});
};
postCodeAjaxAutoComplete('#ajax-postcode', '/ajax.php?do=postcode');
function formatResult(data) {
return data.text;
};
function formatSelection(data) {
return data.text;
};
答案 0 :(得分:1)
请尝试此sqlFiddle
SET @search = "DE20";
SELECT `postcode`,
(SUBSTRING(CONCAT(@search,'^^^^'),1,1)=SUBSTRING(postcode,1,1)) +
(SUBSTRING(CONCAT(@search,'^^^^'),2,1)=SUBSTRING(postcode,2,1)) +
(SUBSTRING(CONCAT(@search,'^^^^'),3,1)=SUBSTRING(postcode,3,1)) +
(SUBSTRING(CONCAT(@search,'^^^^'),4,1)=SUBSTRING(postcode,4,1)) as matches
FROM `postcodes`
HAVING matches > 0
ORDER BY matches DESC,LENGTH(postcode),postcode LIMIT 0,50;