Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
});
like image 209
Dharita Chokshi Avatar asked Feb 13 '19 09:02

Dharita Chokshi


People also ask

What is TypeORM?

TypeORM is a TypeScript ORM (object-relational mapper) library that makes it easy to link your TypeScript application up to a relational database database. TypeORM supports MySQL, SQlite, Postgres, MS SQL Server, and a host of other traditional options.


4 Answers

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

like image 185
H.T. Avatar answered Oct 27 '22 04:10

H.T.


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();
like image 29
Željko Šević Avatar answered Oct 27 '22 06:10

Željko Šević


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

like image 3
Kartik Raja S Avatar answered Oct 27 '22 06:10

Kartik Raja S


await this.createQueryBuilder("Entity name")
  .select('DISTINCT ("column")')
  .getRawMany();
like image 1
Ahmed Mohamed Talaat Avatar answered Oct 27 '22 05:10

Ahmed Mohamed Talaat