【发布时间】:2021-01-20 23:48:20
【问题描述】:
您好,我想在 SQLITE 中编写一个多词部分搜索,例如,如果用户输入“红色”,我将给出名称或颜色或反应性中带有红色的所有抗体,并且如果用户输入“红色 20”我想在名称或颜色或反应性中给出带有红色和 20 的抗体的交集。我已经写了这个,但我认为 SQL 中应该有一些东西可以使它更容易。
const searchMultiWord = (
index: number,
amount: number,
information: string[],
startDate: number,
endDate: number,
) => {
return new Promise<Antibodies[]>((resolve, reject) => {
let antibodies: Antibodies[] = [];
let totalCount: number;
let defaultSql = `SELECT id, name as antibodyName
FROM Antibodies
WHERE id IN (
SELECT id FROM
(
SELECT id FROM Antibodies WHERE name LIKE ?
UNION all
SELECT antiId FROM AssignedColors WHERE name LIKE ?
UNION all
SELECT antiId FROM AssignedReactivities WHERE name LIKE ?
)`;
let defaultParams = [`${startDate}`, `${endDate}`, `${amount}`, `${index}`]
for (let i = 0; i < information.length - 1; i++) {
defaultSql += `INTERSECT
SELECT id FROM
(
SELECT id FROM Antibodies WHERE name LIKE ?
UNION all
SELECT antiId FROM AssignedColors WHERE name LIKE ?
UNION all
SELECT antiId FROM AssignedReactivities WHERE name LIKE ?
)`;
defaultParams.unshift(`%${information[i]}%`, `%${information[i]}%`, `%${information[i]}%`);
}
defaultParams.unshift(`%${information[information.length - 1]}%`, `%${information[information.length - 1]}%`,
`%${information[information.length - 1]}%`);
defaultSql += `) AND dateOfCreation >= ? AND dateOfCreation <= ?
ORDER BY dateOfCreation DESC LIMIT ? OFFSET?;`;
db.serialize(() => {
db.each(defaultSql,
defaultParams
, (err, antibody) => {
if (err) {
return err.message;
} else {
db.all('SELECT name, locations, colorId FROM AssignedColors WHERE antiId = ?', [antibody.id], (err, colors) => {
if (err) {
reject(err.message)
} else {
antibody.colors = colors;
antibodies.push(antibody);
if (totalCount === antibodies.length) {
resolve(antibodies);
}
}
});
}
}, (err, count) => {
if (err) {
reject(err.message)
} else {
if (count === 0) {
resolve(antibodies);
} else {
totalCount = count;
}
}
});
});
});
}
【问题讨论】:
-
您可以根据提供的单词数(即 WHERE name LIKE )构建您的 WHERE 子句和相应的参数?和名字喜欢?和名字喜欢?等就内置 SQL 支持而言,除了可能使用正则表达式(SQLite 本身不支持)之外,我认为您没有太多选择。
标签: sql typescript sqlite node-sqlite3