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

如何在TypeORM中实现MySQL多列IN子句查询?

在TypeORM中实现多列IN查询的最优方案

你原来的写法直接拼接字符串存在SQL注入风险,且不符合TypeORM的参数化查询规范,推荐以下几种更安全优雅的实现方式:

方法一:使用参数化展开(TypeORM 0.3+ 推荐)

TypeORM 0.3及以上版本支持直接传递元组数组作为参数,通过:...语法展开,框架会自动处理占位符和参数绑定:

import { getRepository } from "typeorm";
import { YourEntity } from "./entities/YourEntity";

async function queryMultiColumnIn() {
  const conditions = [['1', '1'], ['2', '2']];
  const repo = getRepository(YourEntity);
  
  const result = await repo.createQueryBuilder("table")
    .where("(table.column1, table.column2) IN (:...conditions)", { conditions })
    .getMany();
  
  return result;
}

方法二:手动构造占位符并绑定参数(兼容旧版本)

如果使用TypeORM 0.2.x版本,可手动构造参数占位符,再逐一绑定参数,同样能避免注入问题:

async function queryMultiColumnInLegacy() {
  const conditions = [['1', '1'], ['2', '2']];
  const repo = getRepository(YourEntity);
  const queryBuilder = repo.createQueryBuilder("table");

  // 构造占位符,如 (:val0_1, :val0_2), (:val1_1, :val1_2)
  const placeholders = conditions.map((_, idx) => 
    `(:val${idx}_1, :val${idx}_2)`
  ).join(',');

  queryBuilder.where(`(table.column1, table.column2) IN (${placeholders})`);

  // 绑定每个参数
  conditions.forEach(([col1Val, col2Val], idx) => {
    queryBuilder.setParameter(`val${idx}_1`, col1Val);
    queryBuilder.setParameter(`val${idx}_2`, col2Val);
  });

  const result = await queryBuilder.getMany();
  return result;
}

方法三:使用Raw函数(灵活适配复杂场景)

对于更复杂的查询场景,可结合Raw函数实现,同样确保参数安全:

async function queryMultiColumnInRaw() {
  const conditions = [['1', '1'], ['2', '2']];
  const repo = getRepository(YourEntity);
  
  const result = await repo.find({
    where: Raw(alias => 
      `${alias}.column1, ${alias}.column2) IN (:...conditions)`, 
      { conditions }
    )
  });
  
  return result;
}

以上方案均遵循TypeORM的参数化查询规范,彻底避免SQL注入风险,同时保持代码的可读性和可维护性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:01:01