我试图从MySQL中的特定列获取所有值,除了我指定忽略的那些。在直接的SQL中它使用
为我工作SELECT login FROM users WHERE login NOT IN ('admin', 'anonymous');
+-----------------+
| login |
+-----------------+
| testUser1 |
| testUser2 |
| testUser3 |
+-----------------+
3 rows in set (0.00 sec)
但我无法使用node-mysql
找到正确的方法var whiteList = ['admin', 'anonymous'];
connection.query('SELECT login FROM users WHERE login NOT IN ?)', whiteList,
function(err, rows) {
if (err) throw err;
console.log(rows);
});
我也尝试过编写数组显式
connection.query('SELECT login FROM users WHERE login NOT IN ("admin", "anonymous")',
function(err, rows) {
if (err) throw err;
console.log(rows);
});
无论哪种方式,我都会收到以下错误
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near ''admin')'
at line 1
所以事实证明我用硬编码节点版本犯了一个愚蠢的错误(感谢你指出Jens)。我错误地引用了它,以下作品
connection.query("SELECT login FROM users WHERE login NOT IN ('admin', 'anonymous')",
function(err, rows) {
if (err) throw err;
console.log(rows);
});
但我仍然无法通过传入数组来实现它,现在我正在尝试
var whiteList = ['admin', 'anonymous'];
whiteList = '(' + whiteList.join(', ') + ')';
connection.query("SELECT login FROM users WHERE login NOT IN ?", [whiteList],
function(err, rows) {
if (err) throw err;
});
原来是一个简单的修复。我在this answer中读到数组被转换为列表,例如[' a'' b']变成' a''' 所以我只需要在括号周围加上括号?
占位符如下
var whiteList = ['admin', 'anonymous'];
connection.query("SELECT login FROM users WHERE login NOT IN (?)", [whiteList],
function(err, rows) {
if (err) throw err;
});