我已经在 MySQL 中存储了一些与用户电子邮件相关的唯一代码作为数组,现在我想使用电子邮件和用户提交的唯一代码来验证用户。我想创建一个查询,在其中可以匹配电子邮件和数据库中存储的唯一 ID,以继续用户。
数据库条目:
["BZFeWwnmr8Rm6tuu","daFJWZCEtp2WzxtD","VV80UQQZ1ym77h0m"]
我已尝试FIND_IN_SET
这是 API 的代码,我已对用户输入的数据进行了字符串化,如果存储了单个唯一值,则返回该值,但如果我获取唯一代码数组,例如 ["BZFeWwnmr8Rm6tuu","daFJWZCEtp2WzxtD","VV80UQQZ1ym77h0m"]
MySQL 查询不工作。
exports.vr_client_detail = function (req, res) {
const JSON_DATA = 'application/json';
if(req.headers['content-type'] === JSON_DATA){
if (req.body) {
var unique_string = JSON.stringify(req.body.unique_string);
var email = req.body.management_email;
db.sequelize.query('SELECT * FROM im_vr_client_activation '+
'WHERE FIND_IN_SET(unique_string, '+"'"+unique_string+"') AND "+
' management_email= ' + "'" + email + "'").then(function(app){
var arr = app[0];
return res.json({response_status:'success', response_code:185, data:arr, response:'Successfully fetch data.'})
});
}else{
return res.json({response_status:'error',response_code:10001,response:'Post data is empty.'});
}
}else{
return res.json({response_status:'error',response_code:10000,response:'Post data is not a json type.'});
}
}
数据没有返回
{
"response_status": "success",
"response_code": 185,
"data": [],
"response": "Successfully fetch data."
}
最佳答案
最好规范化架构,使用多对一表来保存所有唯一字符串,而不是将它们放入单个列中。
但如果您不能这样做,则需要删除 [
和 ]
字符,以便可以使用 FIND_IN_SET()
。
您还应该使用参数化查询来防止 SQL 注入(inject)。请参阅How to create prepared statements in Sequelize?
db.sequelize.query('SELECT * FROM im_vr_client_activation '+
'WHERE FIND_IN_SET(:unique_string, SUBSTR(unique_string, 2, LENGTH(unique_string)-2)) ' +
'AND management_email = :email', {
replacements: { unique_string: unique_string, email: email }
}).then(...)
如果您使用的是 MySQL 5.7 或更高版本,则可以将列的数据类型更改为 JSON
并使用 JSON_CONTAINS()
。在 8.0 中,您可以使用 MEMBER OF
运算符。
关于mysql - 如何获取mysql中存储为数组的字符串数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57919685/