gpt4 book ai didi

javascript - MySQL 条件过滤器处理

转载 作者:行者123 更新时间:2023-12-04 13:06:22 24 4
gpt4 key购买 nike

我正在使用 node.js 并尝试基于多个过滤器进行查询,前提是它们为真

select * from orders ${isFilter ? 'where' : ''} 
${orderId !== undefined && orderId ? `order_id = '${orderId}' or ` : '' }
${receiptId !== undefined && receiptId? `receipt_id = '${receiptId}' or `: '' }
${driver !== undefined && driver ? `driver_id = '${Number(driver)}'` : '' }

这在没有过滤器或所有过滤器都为真但 OR 缺少一个或多个过滤器时会导致问题的情况下工作正常。处理此问题的最佳方法是什么?

最佳答案

这是动态组合查询的伪代码

var clause = 'where';
var query = 'select * from orders';
if (isFilter) { // this statement could be removed
if (orderId !== undefined && orderId) {
query += clause + ' order_id = `${orderId}`';
clause = 'or';
}
if (receiptId !== undefined && receiptId) {
query += clause + ' receiptId = `${receiptId}`';
clause = 'or';
}
if (driver !== undefined && driver) {
query += clause + ' driver = `${driver}`';
clause = 'or'; // this is not really needed, but it could be useful for further filters in future
}
}

关于javascript - MySQL 条件过滤器处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69267930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com