如何在ORDER BY和limit之后动态添加查询参数

时间:2019-06-20 06:37:43

标签: javascript mysql node.js

我正在一个项目上,我需要向查询动态添加参数。我的查询就像:

 let query2 = "SELECT al.*,CONVERT_TZ(al.date_created,'+00:00',?) as date_created, user.first_name as agent_name  FROM `account_log` as `al`  inner join  `user` on user.id = al.user_id  WHERE `al`.`account_id` =  ?  ORDER BY `al`.`id` DESC  limit ?,?";
 let params2 = [tz_offset,account_id, offset, limit];

我想在下面做

query2 += " AND `event_type` = ? ";
params2.push(filter.event_type);

我该如何实现?

1 个答案:

答案 0 :(得分:2)

查询参数必须在ORDER BY和LIMIT之前。

首先添加动态参数,然后添加排序和限制。

let query2 = "SELECT al.*,CONVERT_TZ(al.date_created,'+00:00',?) as date_created, user.first_name as agent_name  FROM `account_log` as `al`  inner join  `user` on user.id = al.user_id  WHERE `al`.`account_id` =  ?  ";
let orderAndLimit = "ORDER BY `al`.`id` DESC  limit ?,?";
let params2 = [tz_offset,account_id];
let orderAndLimitParams = [offset, limit]

query2 += " AND `event_type` = ? ";
params2.push(filter.event_type);

query2 += orderAndLimit;
params2.push(orderAndLimitParams);