简体   繁体   English

NodeJS Mysql 在 where 子句中使用多个字段进行查询

[英]NodeJS Mysql Query with multiple fields in where clause

I'm working with MySQL for a while and also built an API in NodeJS including mySQL for work我正在使用 MySQL 一段时间,还在 NodeJS 中构建了一个 API,包括用于工作的 mySQL

Basically i need a query like "SELECT * FROM table WHERE fieldA=varA AND/OR fieldB=valB"基本上我需要一个像“SELECT * FROM table WHERE fieldA=varA AND/OR fieldB=valB”这样的查询

I'm using "mysql.format(sql, args)" to format my query, so i'm using?我正在使用“mysql.format(sql, args)”来格式化我的查询,所以我正在使用? and??和?? in my Queries.在我的查询中。

I would like to write a basic query, that i could use and feed all the needed fields and values我想编写一个基本查询,我可以使用并提供所有需要的字段和值

I tried the following ways我尝试了以下方法

-> "SELECT * FROM table WHERE?" -> "SELECT * FROM table WHERE?" with "{fieldA: varA, fieldB: varB}" as replacement for?用“{fieldA: varA, fieldB: varB}”代替?

that leads to "SELECT * FROM table WHERE fieldA ='varA', fieldB ='varB'"导致“SELECT * FROM table WHERE fieldA ='varA', fieldB ='varB'”

-> "SELECT * FROM table WHERE?? =?" -> "SELECT * FROM table WHERE??=?" with "['fieldA', 'fieldB']" and "['varA', 'varB']" as replacements用“['fieldA','fieldB']”和“['varA','varB']”作为替换

what leads to "SELECT * FROM table WHERE fieldA , fieldB = 'varA', 'varB'"是什么导致“SELECT * FROM table WHERE fieldAfieldB ='varA','varB'”

For now i "only" need 2 different fields, so i could add fixed "fieldA=? AND/OR fieldB=?"现在我“只”需要 2 个不同的字段,所以我可以添加固定的“fieldA=?和/或 fieldB=?” and fill only the values.并仅填写值。 But i would like a dynamic way and give all the fields i could need in it and also if i use AND or OR in combining.但我想要一种动态的方式,并提供我可能需要的所有字段,如果我使用 AND 或 OR 进行组合。

I didn't find anything like this in the documentation, maybe somebody here had stumbled upon before.我在文档中没有找到这样的东西,也许这里有人以前偶然发现过。 Or might it be the only solution to dynamically add some "AND/OR?? =?"或者它可能是动态添加一些“AND/OR??=?”的唯一解决方案to the query and fill the arguments array with fieldName, values one after the other?查询并用fieldName,值一个接一个地填充arguments数组?

Consider theses are the fields that you need to build your dynamic query string.考虑这些是构建动态查询字符串所需的字段。

var fields = [{fieldName:"A",value:"one",operator:"AND"},{fieldName:"B",value:"two",operator:""}];

Now try building your query string with that array.现在尝试使用该数组构建查询字符串。 For now I have considered only two fields but you can add as per your needs.目前我只考虑了两个字段,但您可以根据需要添加。

var fields = [{fieldName:"A",value:"one",operator:"AND"},{fieldName:"B",value:"two",operator:""}];
var query = "SELECT * FROM table WHERE ";

fields.forEach((f)=>{
    query=query+`${f.fieldName} = ${f.value} `
  if(f.operator!="") query=query+f.operator+" "
})
console.log(query)

I have built a method for this now, with hints from Ameers answer.我现在已经为此建立了一个方法,并附有来自 Ameers 回答的提示。 It will generate a query like它将生成一个查询,如

SELECT * FROM ?? WHERE ??=? AND/OR ??=? AND/OR ??=?

and then will add the fieldName and values to the arguments array for mysql.format然后将 fieldName 和值添加到 mysql.format 的参数数组中

var fieldValues = [
  { field: 'command', value: command.command, operator: 'OR' },
  { field: 'alias', value: command.command, operator: 'OR' }
];

exists(fieldValues) {
  let query = 'SELECT * FROM ??';
  let args = ['tablename'];
  for (let i = 0; i < fieldValues.length; i++) {
    let operator = i == 0 ? 'WHERE' : fieldValues[i].operator;
    query += ` ${operator} ?? = ?`;
    args.push(fieldValues[i].field);
    args.push(fieldValues[i].value);
  }

  return mysql.query(query, args);
}

mysql.query() here is my wrapper around mysql.connection.query and using promises mysql.query()这里是我围绕mysql.connection.query和使用承诺的包装器

Maybe there is a better builtin method, but i didn't find one yet and this way i can still use the builtin mysql-formatter function.也许有更好的内置方法,但我还没有找到,这样我仍然可以使用内置的 mysql-formatter 函数。

Consider, that you have fields in DB like first_name , last_name , personal_email, work_email and office_name .考虑一下,您在数据库中有first_namelast_namepersonal_email, work_emailoffice_name等字段。 and you want to get all result matching with search fields.并且您想获得与搜索字段匹配的所有结果。 ie let search = req.query.search.let search = req.query.search. It will become easy with ORM like Objection.js So the query will be like this using objection.js像 Objection.js 这样的 ORM 会变得很容易所以使用 objection.js 的查询会像这样

if (search) {
    table_name.where('column_name.last_name', 'like', `%${search}%`) 
        .orWhere('column_name.first_name', 'like', `%${search}%`) 
        .orWhere('column_name.personal_email', 'like', `%${search}%`) 
        .orWhere('column_name.work_email', 'like', `%${search}%`) 
        .orWhere('column_name.office_name', 'like', `%${search}%`)
}

Note: This code is in nodejs and you can also use table_name you can also add model_name .注意:此代码在 nodejs 中,您也可以使用table_name也可以添加model_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM