如何在 Knex JS 中使用 IS NOT NULL

How to use IS NOT NULL in Knex JS

我正在尝试使用 knex 创建以下查询:

SELECT * FROM users group by users.location having users.photo is not null

如下:

knex("users").groupBy("users.location").having("users.photo", "IS NOT", "Null")

我收到以下错误:

The operator IS NOT is not permitted

我浏览了他们的文档,但找不到任何有用的信息。

你试过了吗:

knex("users").whereNotNull("photo").groupBy("location")

根据docs.havingRaw是你需要的:

knex("users").groupBy("users.location").havingRaw("users.photo IS NOT ?", [null]);

另一方面,立即执行 knex.raw,除非在此特定情况下使用构建器还有任何剩余优势。

文档有答案。有whereNullwhereNotNullhavingNullhavingNotNull等。

来自DOCS:

havingNull — .havingNull(column)
Adds a havingNull clause to the query.

knex.select('*').from('users').havingNull('email')

输出:

select * from `users` having `email` is null

havingNotNull — .havingNotNull(column)
Adds a havingNotNull clause to the query.

knex.select('*').from('users').havingNotNull('email')

输出:

select * from `users` having `email` is not null

使用 knex 查询实验室尝试一下:http://michaelavila.com/knex-querylab/