Knex.js SQL 构建器速查表
Knex 是 Node.js SQL 查询构建器,支持 PostgreSQL、MySQL、SQLite,整理常用 API。
返回 数据库查询数据 6
knex("users").select("*")SELECT * FROM users
knex("users").select("name", "email")SELECT name, email FROM users
knex("users").where("age", ">", 18)WHERE age > 18
knex("users").where({ status: "active" })WHERE status = active
knex("users").orderBy("created_at", "desc")ORDER BY created_at DESC
knex("users").limit(10).offset(20)LIMIT 10 OFFSET 20
插入数据 3
knex("users").insert({ name: "John", email: "john@example.com" })插入单条
knex("users").insert([{ name: "A" }, { name: "B" }])批量插入
knex("users").insert(data).returning("id")插入并返回 ID
更新与删除 3
knex("users").where("id", 1).update({ name: "Jane" })更新指定记录
knex("users").where("id", 1).del()删除指定记录
knex("users").truncate()清空表
Join 关联 3
knex("users").join("posts", "users.id", "posts.user_id")INNER JOIN
knex("users").leftJoin("posts", "users.id", "posts.user_id")LEFT JOIN
knex("users").join("posts", function() { this.on("users.id", "=", "posts.user_id").orOn("users.email", "=", "posts.email") })多条件 JOIN
聚合与分组 5
knex("users").count("id")COUNT(id)
knex("users").sum("amount")SUM(amount)
knex("users").max("age")MAX(age)
knex("users").groupBy("status")GROUP BY status
knex("users").groupBy("status").having(knex.raw("count(*) > ?", [5]))HAVING count > 5
事务 2
knex.transaction(async (trx) => { await trx("users").insert(data) })自动提交/回滚事务
const trx = await knex.transaction(); await trx.commit() / trx.rollback()手动控制事务
💡 提示
- Knex 支持 PostgreSQL、MySQL、MariaDB、SQLite、MSSQL。
- 查询构建器返回 Promise,需要 await 或 .then()。
- knex.raw("SQL") 执行原生 SQL,适合复杂查询。
- Migration 用 knex.migrate.make() 创建,knex.migrate.latest() 执行。
- 连接池默认启用,配置 pool: { min: 2, max: 10 } 调整。