使用node-mysql查询多行

时间:2013-07-06 04:07:18

标签: mysql sql node.js node-mysql

此问题与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

1 个答案:

答案 0 :(得分:1)

不要直接将变量添加到sql字符串中,而是让mysql包为您完成。这通常可以解决像这样的问题,并且还可以防止SQL注入。

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

例如

connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  // ...
});