如何在TypeORM的find查询中获取distinct去重值
TypeORM实现DISTINCT去重查询的解决方案
TypeORM的find方法确实不直接支持distinct配置,你可以通过以下两种常用方式实现需求:
方案1:使用QueryBuilder(推荐)
QueryBuilder是TypeORM提供的灵活查询构造器,原生支持distinct和指定返回字段,代码示例如下:
const result = await this._itemRepository .createQueryBuilder('clothes') .select(['clothes.name', 'clothes.description', 'clothes.style', 'clothes.spec2', 'clothes.div']) .distinct(true) .where('clothes.name = :name', { name: 'CMD' }) .andWhere('clothes.div IN (:...divs)', { divs: ['B01', 'B06', 'B07', 'B09'] }) .getRawMany(); // 如果你需要返回完整的实体对象,可将getRawMany替换为getMany
注意:明确指定需要查询的字段后再开启去重,和你目标SQL的逻辑完全一致。
方案2:直接执行原生SQL
如果你更习惯手写SQL语句,可以直接调用Repository的query方法执行原生查询:
const result = await this._itemRepository.query( `SELECT DISTINCT name, description, style, spec2, div FROM clothes WHERE name = ? and div in (?, ?, ?, ?)`, ['CMD', 'B01', 'B06', 'B07', 'B09'] );
这种方式适合复杂查询场景,注意要使用参数绑定避免SQL注入风险,不要直接拼接用户输入的参数。
内容的提问来源于stack exchange,提问作者dilusha_dasanayaka
相关产品推荐
相关产品推荐

