js实现sql条件查询
使用纯JavaScript实现SQL条件查询
在JavaScript中模拟SQL条件查询可以通过数组的filter方法实现。假设有一个对象数组作为数据源,可以通过以下方式实现条件筛选:
const data = [
{ id: 1, name: 'Alice', age: 25, department: 'HR' },
{ id: 2, name: 'Bob', age: 30, department: 'IT' },
{ id: 3, name: 'Charlie', age: 28, department: 'IT' }
];
function sqlWhere(data, conditions) {
return data.filter(item => {
return Object.entries(conditions).every(([key, value]) => {
if (typeof value === 'function') {
return value(item[key]);
}
return item[key] === value;
});
});
}
实现复杂条件查询
对于更复杂的SQL条件(如AND、OR、LIKE等),可以扩展上述函数:
function sqlQuery(data, whereClause) {
return data.filter(item => {
// 处理AND条件
if (whereClause.AND) {
return whereClause.AND.every(cond => evaluateCondition(item, cond));
}
// 处理OR条件
if (whereClause.OR) {
return whereClause.OR.some(cond => evaluateCondition(item, cond));
}
// 处理单个条件
return evaluateCondition(item, whereClause);
});
}
function evaluateCondition(item, condition) {
const [key, operator, value] = condition;
switch(operator) {
case '=': return item[key] === value;
case '!=': return item[key] !== value;
case '>': return item[key] > value;
case '<': return item[key] < value;
case '>=': return item[key] >= value;
case '<=': return item[key] <= value;
case 'LIKE':
const regex = new RegExp(value.replace('%', '.*'), 'i');
return regex.test(item[key]);
default: return false;
}
}
使用示例
// 简单条件查询
const result1 = sqlWhere(data, { department: 'IT', age: 30 });
// 复杂条件查询
const result2 = sqlQuery(data, {
OR: [
['age', '>', 28],
['name', 'LIKE', '%ice%']
]
});
使用第三方库实现
对于更完整的SQL查询功能,可以考虑使用专门库:

-
AlaSQL - 内存SQL数据库
const res = alasql('SELECT * FROM ? WHERE age > 25', [data]); -
TaffyDB - 类SQL查询库

const db = TAFFY(data); const res = db({age: {gt: 25}}).get(); -
Linq.js - LINQ风格查询
const res = Enumerable.from(data) .where(x => x.age > 25) .toArray();
性能优化建议
对于大型数据集,纯JavaScript过滤可能性能不足。可以考虑以下优化:
- 使用Web Workers进行后台处理
- 实现索引机制加速查询
- 考虑使用位图索引等高级数据结构
- 对于不变数据集,预先排序可以加速范围查询
以上方法提供了从简单到复杂的JavaScript实现SQL条件查询的方案,可根据实际需求选择适合的方式。






