Typeorm Queryrunner Select Distinct

Below is my SQL query:

Select distinct ports.port_name from orders left join port_master on orders.officeId = ports.portId;

How to write the above SQL using typeorm query runner to select the distinct port name? Below syntax fetches all the ports

await queryRunner.manager.find(Orders, {
  relations: ["ports"],
  where: filter
}).then((result: any) => {
  orders = result;
});

4 Answers

Another way to do this is by using the query builder and distinct method

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

In case you are using Postgresql you can use distinctOn and the query looks like this:

await getRepository(Feed)
      .createQueryBuilder('feed')
      .where({ uploaderId: In([1,2,3,4]) })
      .distinctOn(['feed.uploaderId'])
      .orderBy({ 'feed.uploaderId': 'ASC', 'feed.createdAt': 'DESC' })
      .getMany()

In the above example there is a Feed table which I want to get the rows which Id exists in the given array and also distinct the values by uploaderId and then sort it by createdAt date

Instead of using Raw query you may also use the below mentioned query builder

await getManager().createQueryBuilder(orders , "odrs")
.leftJoinAndSelect(ports, "pts", "odrs.officeId = pts.portId")
.select('DISTINCT odrs.port_name', 'port_name')
.orderBy("odrs.port_name", "ASC")
.getRawMany();

Thank You

await this.createQueryBuilder("Entity name")
  .select('DISTINCT ("column")')
  .getRawMany();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest