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

yptwkmov  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(292)

我有两个数组如下

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

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

fieldarray和dataarray中元素的每次计数都会相同,但元素会不同,在数据数组中,某些元素可以为空,
我必须在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语句

gcuhipw9

gcuhipw91#

使用reduce准备一个带有数据的map-first链接字段

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

现在使用 join 以及 map ```
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注入,将值作为参数传递,而不是使用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;
// ...
});

ncgqoxb0

ncgqoxb02#

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 ")} `;

只需遍历dataarray,检查字段是否为空,并将其连接到结果查询。始终确保舒尔不会受到sql注入的影响!

相关问题