0

此问题与 node-mysql 有关。

下面的代码我好像有问题,好像和用户定义变量的使用有关。呈现的查询在任何 mysql IDE 中运行良好,返回多条记录。然而,当由 node-mysql 执行时,它只返回一条记录。

我已经验证,消除指定 T3.gender_rank 的 WHERE 子句会在 node-mysql 和我的 mysql IDE 中创建可预测的结果。

以前是否提出过这个问题,还是我做错了什么?

var mysql = require('mysql'); // Establish SQL Support
var sql =
    "select team, `div`, sum(points) AS teampoints "+
    "from ( "+
    "   select "+
    "       *, "+
    "       (@genderRank := CASE WHEN @genderTMP <> gender THEN 1 ELSE @genderRank+1 END) AS gender_rank, "+
    "       (@genderTMP := gender) AS _gt "+
    "   from ( "+
    "       select * "+
    "       from racepoints "+
    "       WHERE "+
    "           ltrim(rtrim(race)) = '"+data.eventName+"' AND "+
    "           racedate = '"+getSimpleDate(new Date(data.eventStart))+"' "+
    "       ORDER BY team,gender,points DESC "+
    "   ) T1, "+
    "   (select @genderRank:=0 AS gender_rank_start) T2 "+
    ") T3 "+
    "WHERE "+
    "   (T3.gender_rank <= 4 AND rtrim(ltrim(`div`)) = 'D2') OR "+
    "   (T3.gender_rank <= 3 AND rtrim(ltrim(`div`)) = 'D1') "+
    "GROUP BY team, `div` "+
    "ORDER BY `div`, teampoints DESC, team";


var db = new mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : 'admin',
    database : 'nps',
    multipleResults : true
});
db.connect();
db.query(
    sql,
    function(err,rows,fields){
        if(err){
            console.log(err);
            return;
        }
        console.log(rows);
    }
);
db.end();

SQL 数据库文件也可在此处获得:https ://snipt.net/download/dde8b4b5ce8cd5fca21ac2334bae634f/-5369.sql

4

1 回答 1

1

与其直接将变量添加到 sql 字符串中,不如让 mysql 包为您完成。这通常可以解决此类问题,并额外防止 SQL 注入。

这是通过使用问号(每个变量一个)后跟一组变量来完成的。

例如

connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  // ...
});
于 2013-07-06T18:14:08.240 回答