1

npm 上的 node-mysql 文档(https://npmjs.org/package/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) {
        ...
    });

但无济于事。我想知道是否有办法做到这一点?

4

1 回答 1

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) {
  ...
});
于 2013-05-20T21:53:40.160 回答