是否可以在第二个或任何下一个参数完成mySQL查询但首先是null
?
例如,我为单个项目datereport
生成基于给定日期(itemreport
)的报告。
现在,当前端没有选择任何项目且其req.query.itemreport
获得null
时,考虑到用户要求所有项目而不是单个项目而不停止,则必须执行查询的其余部分执行因为它获得null
参数(itemreport
)。
reportsdateres.post(function(req, res, next) {
datereport = req.query.datereport;
itemreport = req.query.itemreport; // this can be null for querying all items
req.getConnection(function(err, conn) {
if (err) return next("Cannot Connect");
var query = conn.query("SELECT SUM(total_profit) AS fee_total FROM transactions WHERE date_created = ? AND item = ?", [datereport, itemreport], function(err, rows) {
// ^^^^^^^^^^^^
// do myStuff
});
});
});
答案 0 :(得分:1)
reportsdateres.post(function(req, res, next) {
datereport = req.query.datereport;
itemreport = req.query.itemreport; // this can be null for querying all items
req.getConnection(function(err, conn) {
if (err) return next("Cannot Connect");
var queryString = "SELECT SUM(total_profit) AS fee_total FROM transactions WHERE date_created = ? ";
var queryParams = [];
queryParams.push(datereport);
if(itemreport){
queryString += ' AND item = ?'
queryParams.push(itemreport);
}
var query = conn.query(queryString, queryParams, function(err, rows) {
// do yourStuff
});
});
});
添加了修复,附加了查询字符串。即使我错过了它:)
答案 1 :(得分:0)
reportsdateres.post(function(req, res, next) {
datereport = req.query.datereport;
itemreport = req.query.itemreport; // this can be null for querying all items
req.getConnection(function(err, conn) {
if (err) return next("Cannot Connect");
if (itemreport==null || itemreport=='') {
var sql = "SELECT SUM(total_profit) AS fee_total FROM transactions WHERE date_created = ?";
var params = [datereport];
}else{
var sql = "SELECT SUM(total_profit) AS fee_total FROM transactions WHERE date_created = ? AND item = ?";
var params = [datereport, itemreport];
}
var query = conn.query(sql, params, function(err, rows) {
// ^^^^^^^^^^^^
// do myStuff
});
}); });
答案 2 :(得分:0)
reportsdateres.post(function(req, res, next) {
datereport = req.query.datereport;
itemreport = req.query.itemreport; // this can be null for querying all items
req.getConnection(function(err, conn) {
if (err) return next("Cannot Connect");
var query = conn.query("SELECT SUM(total_profit) AS fee_total FROM transactions WHERE date_created = ? AND item = COALESCE(?, item)", [datereport, itemreport], function(err, rows) {
// do myStuff
});
});
});
COALESCE(我们可以在代码中删除if else)函数将第一个参数考虑在内,如果它不为null,否则它将比较item列的值与其自身,更多细节请访问:https://www.w3schools.com/sql/sql_isnull.asp < / p>