Node.js 实现多条件博客搜索 - id, title, author, classify
可以使用SQL的OR操作符来实现多个条件的搜索。以下是修改后的代码:
exports.getSelectBlogs = (req, res) => {
const info = req.body;
const sqlStr = `SELECT * FROM blogs_info WHERE id LIKE ? OR title LIKE ? OR author LIKE ? OR classify LIKE ?`;
const searchStr = `%${info.keyword}%`;
db.query(sqlStr, [searchStr, searchStr, searchStr, searchStr], (err, results) => {
if (err) return res.cc(err);
if (results.length === 0) return res.cc("查询失败,没有匹配的文章");
res.send({
status: 0,
message: "查询成功",
data: results
});
});
};
在这个修改后的代码中,我们使用了LIKE操作符来进行模糊搜索。LIKE操作符可以用来匹配字符串中的部分内容。我们使用%符号来表示任意字符的通配符。%${info.keyword}%表示搜索结果中包含info.keyword的部分。通过将搜索字符串传递给db.query方法的第二个参数,我们可以将搜索字符串插入到SQL查询中。
原文地址: https://www.cveoy.top/t/topic/pKRA 著作权归作者所有。请勿转载和采集!