我当前的查询如下所示:
router.get('/search?', function(req, res, next) {
var title = req.query.title;
var sql = "SELECT * from users WHERE title = ?";
connection.query(sql, [title], function (error, results, fields) {
res.json({"status": 200, "error": null, "response": results});
});
});
如果我输入:
localhost:4001/api/v1/users/search?title=mr
但是如何用OR搜索多个值...像这样:
localhost:4001/api/v1/users/search?title=mr,mrs,dr
答案 0 :(得分:2)
基本上,
如果查询参数中有多个逗号分隔值,则可以按,
拆分它们并使用sql IN clause
。
如果您有一个参数值,那么您的方法已经正常工作。
router.get('/search?', function(req, res, next) {
var title = req.query.title;
var sql;
if (title.includes(",")) {
var params = title.split(",");
sql = "SELECT * from users WHERE title IN " + params;
} else {
sql = "SELECT * from users WHERE title = " + title;
}
connection.query(sql, function (error, results, fields) {
res.json({"status": 200, "error": null, "response": results});
});
});