You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeORM中编写排除多个指定ID的查询语句?

在TypeORM中实现排除指定ID的查询

要实现你需要的SELECT * FROM Users WHERE id <> 3 and id <> 8 and id <> 23;效果,有几种常用写法,推荐用更简洁高效的NOT IN替代多个AND <>:

方法1:使用QueryBuilder(灵活可控)

这是TypeORM中最灵活的查询方式,适配复杂场景:

import { getRepository } from "typeorm";
import { User } from "./entities/User"; // 替换为你的User实体路径

async function fetchUsersExcludingIds() {
  const excludedIds = [3, 8, 23];
  const targetUsers = await getRepository(User)
    .createQueryBuilder("user")
    .where("user.id NOT IN (:...excludedIds)", { excludedIds })
    .getMany();
  return targetUsers;
}

如果要严格对应原SQL的多个<>条件,也可以这样写:

const targetUsers = await getRepository(User)
  .createQueryBuilder("user")
  .where("user.id <> :id1", { id1: 3 })
  .andWhere("user.id <> :id2", { id2: 8 })
  .andWhere("user.id <> :id3", { id3: 23 })
  .getMany();

方法2:使用Repository的find方法(简洁高效)

针对简单查询,直接用find方法配合TypeORM的查询操作符更直观:

import { getRepository, Not, In } from "typeorm";
import { User } from "./entities/User";

async function fetchUsersExcludingIds() {
  const excludedIds = [3, 8, 23];
  const targetUsers = await getRepository(User).find({
    where: {
      id: Not(In(excludedIds))
    }
  });
  return targetUsers;
}

注意:Not和In是TypeORM提供的查询操作符,需要提前导入。

内容的提问来源于stack exchange,提问作者Haim_t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 10:17:03