Node.js API with express& mysql - 在搜索参数中搜索多个值

时间:2018-02-21 11:03:12

标签: mysql node.js express

我当前的查询如下所示:

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

1 个答案:

答案 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});
    });
});