使用具有重叠列名称的联接的Options参数转义查询

时间:2012-12-16 18:21:46

标签: node.js node-mysql mysql-escape-string

npm(https://npmjs.org/package/mysql)上的node-mysql文档有一个选项可以在表连接中重叠列名,如下所示:

var options = {sql: '...', nestTables: true};
connection.query(options, function(err, results) {
  /* results will be an array like this now:
  [{
    table1: {
      fieldA: '...',
      fieldB: '...',
    },
    table2: {
      fieldA: '...',
      fieldB: '...',
    },
  }, ...]
  */
});

转义查询标识符格式将第二个参数传递给清除标识符的connection.query()

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

我想知道如何将这两者结合使用?假设您需要在连接中转义标识符,但想要声明嵌套表的选项:

var sqlString: 'SELECT * FROM TableOne INNER JOIN TableTwo ON TableOne.id = TableTwo.tableone_id WHERE TableOne.id = ?';
var options = {sql: sqlString, nestTables: true};
connection.query(options, function(err, results) {
    ...
});

我试图将转义值作为connection.query()中的第二个参数传递,如下所示:

var sqlString: 'SELECT * FROM TableOne INNER JOIN TableTwo ON TableOne.id = TableTwo.tableone_id WHERE TableOne.id = ?';
    var options = {sql: sqlString, nestTables: true};
    connection.query(options, 1, function(err, results) {
        ...
    });

但无济于事。我想知道是否还有这样做?

1 个答案:

答案 0 :(得分:0)

如果您阅读代码,第66行就有一个IF块

if (typeof sql === 'object') {
  options = sql;
  cb      = values;
  values  = options.values;
}

意思是你会做

var sqlString: 'SELECT * FROM TableOne INNER JOIN TableTwo ON TableOne.id = TableTwo.tableone_id WHERE TableOne.id = ?';
var options = {sql: sqlString, nestTables: true, values: [1]};
connection.query(options, function(err, results) {
  ...
});