nodejs中的“where in”MySQL查询

问题描述 投票:0回答:3

我需要使用“WHERE IN”进行MySQL查询。 这是我的查询:

var myQuery = 'SELECT uid FROM ' +tableName+ ' where Gender IN (' + Info.Gender.join() + ')';

如果我打印

Info.Gender
它将是 ['Male', 'Female'],作为字符串。 但当查询完成后,它会说

SELECT uid FROM appUsers where Gender IN (Male, Female)

但应该是:

SELECT uid FROM appUsers where Gender IN ('Male', 'Female')

这意味着它将 Female 不作为字符串。

有什么想法吗?

javascript mysql node.js where-clause
3个回答
27
投票

您应该使用查询转义(前提是您使用

node-mysql
):

var myQuery = 'SELECT uid FROM ?? where Gender IN (?)';
connection.query(myQuery, [ tableName, Info.Gender ], ...);

2
投票

您的查询中需要单引号:

var myQuery = "SELECT uid FROM " +tableName+ " where Gender IN ('" + Info.Gender.join("','") + "')";

0
投票

您也可以将

Info.Gender
作为数组传递:

var myQuery = `SELECT uid FROM users where Gender IN (?)`
var arrayData = ['Male', 'Female']
connection.query(myQuery, [arrayData])
© www.soinside.com 2019 - 2024. All rights reserved.