javascript - TypeORM Custom Repository, select distinct values from specified column - Stack Overflow

In my backend using nestjs + typeorm + postgresql I have a CustomRepository and want to repalce some pl

In my backend using nestjs + typeorm + postgresql I have a CustomRepository and want to repalce some plain sql queries.

This is what I have

const sqlQuery = `SELECT DISTINCT "myColumn" FROM "myTable"`
const sqlRes = await this.query(sqlQuery);

I am trying to get something like this

this.find({select:["myColumn"]}); // note the missing DISTINCT

But this is giving me the plete column but I want just the DISTINCT values.

I found a lot of weird createQueryBuilder().select(DISTINCT "myColumn" FROM "...... etc... solutions, which are not really giving my any benefit over my working solution.

In my backend using nestjs + typeorm + postgresql I have a CustomRepository and want to repalce some plain sql queries.

This is what I have

const sqlQuery = `SELECT DISTINCT "myColumn" FROM "myTable"`
const sqlRes = await this.query(sqlQuery);

I am trying to get something like this

this.find({select:["myColumn"]}); // note the missing DISTINCT

But this is giving me the plete column but I want just the DISTINCT values.

I found a lot of weird createQueryBuilder().select(DISTINCT "myColumn" FROM "...... etc... solutions, which are not really giving my any benefit over my working solution.

Share Improve this question edited Dec 2, 2021 at 13:56 Audwin Oyong 2,5313 gold badges19 silver badges36 bronze badges asked May 4, 2020 at 10:39 FuzzyTemperFuzzyTemper 7836 gold badges10 silver badges25 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6

You could do:

await getManager().createQueryBuilder('entity')
  .select('column')
  .distinct(true)
  .getRawMany();

For some reason getMany or getCount doesn't work for distinct. As 0xCAP said above:

await getManager().createQueryBuilder('entity')
  .select('column')
  .distinct(true)
  .getRawMany();

If you want to keep other columns (as your question), just use addSelect instead of select

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742288702a4415791.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信