[英]Finding null values with .whereIn
我用 Knex 构建了一个查询,如下所示:
knex('discounts')
.where((builder) => {
builder
.where('product_code', productCode)
.where((builder1) => {
builder1
.andWhere('account_code', customer)
.orWhere('account_code', null);
});
})
.select('*');
一切正常,但我觉得.where
语句太长了,所以尝试使用.whereIn
function,那时我意识到它不起作用:
knex('discounts')
.where((builder) => {
builder
.where('product_code', productCode)
.whereIn('account_code', [customer, null]);
})
.select('*');
我知道我们不能在原始 SQL 中将null
与IN
一起使用,应该这样做:
WHERE
(columnName IN ('value1', 'value2', 'value3') OR columnName IS NULL)
我的问题:我的初始查询是实现此目的的唯一方法,还是在使用 Knex 时有任何替代方法可以将.whereIn
与null
一起使用?
更优化我会做
knex('discounts')
.where('product_code', productCode)
.where((builder1) => {
builder1
.whereIn('account_code', customer)
.orWhereNull('account_code');
});
})
.then();
添加了内联where
和.orWhere('account_code', null);
被替换为orWhereNull
。 提示如果你 select *
不需要写select
,默认查询生成器是 select。 在 whereIn 数组中的值可以是一个/多个具有 null 值的变量,knex 不能将 whereIn 转换为 => whereIn or where Is NOT NULL
你对第一个查询是正确的,额外的内联 function 是不必要的。 如果我正确理解您的要求,这里只需要一个分组。 所以这很好:
db("discounts")
.where("product_code", productCode)
.where(qb =>
qb.where("account_code", customer).orWhereNull("account_code")
)
这将生成以下 SQL:
SELECT * FROM "discounts"
WHERE "product_code" = ?
AND ("account_code" = ? OR "account_code" IS NULL)
如果您想更明确,可以使用.andWhere
,但它不会更改生成的 SQL:
.where("product_code", productCode)
.andWhere(qb =>
顺便说一句(如果您还没有发现),您可以通过添加.debug()
来查看 SQL 将为任何 Knex 链执行的内容。 如果您正在重构或只是好奇,这可能会很方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.