如何使用动态数组进行mysql查询

时间:2018-01-06 10:39:04

标签: javascript mysql arrays node.js

我有两个数组如下

var fieldarray =  [ 'category',
                    'bookid',
                    'bookauthor',
                    'booktitle',
                    'price',
                    'publication',
                    'publication_date' ]

var dataarray =  [ 'fantasy',
                    '',
                    'JKR',
                     '',
                     '',
                     '',
                     '' ]

每次元素数量在fieldarray和dataarray中都是一样的,但元素会有所不同,在数据数组中一些元素可能是空的,

我必须在mysql语句中使用这些数组。我期望mysql查询如下

select category,bookid,bookauthor,booktitle,price,publication,publication_date from tbl_books where category like '%fantasy%' OR bookauthor like '%JKR%'

如何根据nodejs中的fiedarray和dataarray元素动态创建mysql语句

2 个答案:

答案 0 :(得分:0)

 var filters = [];

 dataarray.forEach((val, index) => {
   if(val)
    filters.push(`${fieldarray[index]} like '%${val}%'`);
 });

var result = `select ${fieldarray.join(",")} from tbl_books where ${filters.join(" OR ")} `;

只需迭代数据阵列,检查字段是否为空,并将其连接到生成的查询。始终保证您不受SQL注入的影响!

答案 1 :(得分:0)

首先使用reduce

准备地图,首先将字段与数据相关联
var map = fieldarray.reduce( ( a, c, i ) => ( dataarray[i] && (a[c] = dataarray[i]), a ) , {}) ; 

现在使用joinmap

动态准备查询
var query = "SELECT " + fieldarray.join(" , ") + "from tbl_books where " + Object.keys(map).map(f => (f + " like '%" + map[f] + "%'")).join(" AND ");

<强>演示

var fieldarray = ['category',
  'bookid',
  'bookauthor',
  'booktitle',
  'price',
  'publication',
  'publication_date'
]

var dataarray = ['fantasy',
  '',
  'JKR',
  '',
  '',
  '',
  ''
];
var map = fieldarray.reduce((a, c, i) => (dataarray[i] && (a[c] = dataarray[i]), a), {});

var query = "SELECT " + fieldarray.join(" , ") + "from tbl_books where " + Object.keys(map).map(f => (f + " like '%" + map[f] + "%'")).join(" AND ");

console.log(query);

为了避免sql-injection将值作为params传递,而不是使用mysqljs

在查询中对它们进行硬编码
var query = "SELECT " + fieldarray.join(" , ") + "from tbl_books where " + Object.keys(map).map(f => (f + " like ?")).join(" AND ");

connection.query( query, Object.values(map), function (error, results, fields) {
  if (error) throw error;
  // ...
});