使用 .whereIn 查找空值
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
函数,然后我意识到它不起作用:
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 数组中的值可以是 one/multiple 具有空值的变量,knex 不会将 whereIn 转换为 =>whereIn or where Is NOT NULL
你对第一个查询是正确的,额外的内联函数是不必要的。如果我正确理解您的要求,这里实际上只需要一个分组。所以这很好:
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()
查看任何 Knex 链将执行的 SQL。如果您正在重构或只是好奇,这会很方便。
我使用 Knex 构建了一个查询,如下所示:
knex('discounts')
.where((builder) => {
builder
.where('product_code', productCode)
.where((builder1) => {
builder1
.andWhere('account_code', customer)
.orWhere('account_code', null);
});
})
.select('*');
一切正常,但我觉得 .where
语句太长所以尝试使用 .whereIn
函数,然后我意识到它不起作用:
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 数组中的值可以是 one/multiple 具有空值的变量,knex 不会将 whereIn 转换为 =>whereIn or where Is NOT NULL
你对第一个查询是正确的,额外的内联函数是不必要的。如果我正确理解您的要求,这里实际上只需要一个分组。所以这很好:
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()
查看任何 Knex 链将执行的 SQL。如果您正在重构或只是好奇,这会很方便。