我正在开发一个 PWA,我有一个数据库,我想像这样查询:
SELECT * FROM plants WHERE (plant_genus LIKE 'Ab%') AND (plant_species LIKE 'pr%')
索引定义如下:
surveyPlantsOS.createIndex("multiple", ['plant_genus', 'plant_species', 'occurrence'], { unique: false });
我尝试过以下方法:
const midRange = IDBKeyRange.bound(['Ab','pr'], ['Ab'+'\uffff','pr'+'\uffff']);
let cursor = await dbTT.getAllFromIndex('tt_survey_plants', 'multiple', midRange)
这在第一列上工作正常,但第二列被忽略。
我希望“Ab”在“plant_genus”列上搜索,“pr”在“plant_species”列上搜索
任何帮助将不胜感激。
暂时我已经通过这样解析结果集解决了这个问题:
if (cursor) {
for (const [key, value] of Object.entries(cursor)) {
if (arrChars.length > 1) {
if (value.plant_species.indexOf(arrChars[1]) != -1) {
//console.log('found ', `${value.plant_genus} ${value.plant_species} `)
data[value.plant_genus+' '+value.plant_species] = null
}
}
else
data[value.plant_genus+' '+value.plant_species] = null
}
}
在 IndexedDB 中,您不能像使用 MySQL 的 LIKE 那样直接使用带有通配符的类似 SQL 的查询。相反,您需要使用 IndexedDB 的可用方法和功能进行搜索。要实现您想要的多列搜索,您可以使用以下方法
const index1 = dbTT.createIndex('genusIndex', 'plant_genus');
const index2 = dbTT.createIndex('speciesIndex', 'plant_species');
const genusResults = await index1.getAll('Ab');
const speciesResults = await index2.getAll('pr');
// Combine the results as needed
const combinedResults = /* your logic to combine genusResults and speciesResults */;
此方法将“plant_genus”和“plant_species”的搜索分开,并允许您根据您的要求组合结果。您可能需要执行额外的过滤和逻辑来根据需要合并结果。