Skip to content

Strange behavior when using limit with relations (joins) #3967

Closed

Description

@avilesj

Issue type:

[ ] question
[X] bug report
[ ] feature request
[ ] documentation issue

Database system/driver:

[ ] cordova
[ ] mongodb
[ ] mssql
[ ] mysql / mariadb
[ ] oracle
[X] postgres
[ ] cockroachdb
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo

TypeORM version:

[ ] latest
[ ] @next
[0.2.7] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

Short version

When using joins, limit() does not seem to work properly.

Long Version

I have the following query:

      return this.branchRepo.createQueryBuilder("branches")
      .innerJoinAndSelect("branches.branchSchedules", "branch_schedules", "branch_schedules.branch_id = branches.id")
      .leftJoinAndSelect("branches.branchFeature", "branchFeature", "branchFeature.branch_id = branches.id")
      .leftJoinAndSelect("branchFeature.feature", "features")
      .orderBy("branches.is_all_day", "DESC")
      .addOrderBy("branch_schedules.end_time::time", "DESC")
      .addOrderBy("branch_schedules.day", "DESC")
      .addOrderBy(`(case when branch_schedules.day = 'holiday' then 1
                         when branch_schedules.day = 'sunday' then 2
                         when branch_schedules.day = 'saturday' then 3
                         when branch_schedules.day = 'weekday' then 4
                         end)`,
                  "ASC")
      .addOrderBy("branch_schedules.start_time::time", "ASC")
      .limit(5)
      .getMany();

Which produces the following query:

SELECT "branches"."estimated_time" AS "branches_estimated_time", "branches"."is_all_day" AS "branches_is_all_day", "branches"."address" AS "branches_address", "branches"."id" AS "branches_id", "branches"."name" AS "branches_name", "branches"."latitude" AS "branches_latitude", "branches"."has_extended_schedule" AS "branches_has_extended_schedule", "branches"."created_at" AS "branches_created_at", "branches"."updated_at" AS "branches_updated_at", "branches"."longitude" AS "branches_longitude", "branches"."code" AS "branches_code", "branches"."phone" AS "branches_phone", "branch_schedules"."end_time" AS "branch_schedules_end_time", "branch_schedules"."id" AS "branch_schedules_id", "branch_schedules"."start_time" AS "branch_schedules_start_time", "branch_schedules"."updated_at" AS "branch_schedules_updated_at", "branch_schedules"."created_at" AS "branch_schedules_created_at", "branch_schedules"."day" AS "branch_schedules_day", "branch_schedules"."branch_id" AS "branch_schedules_branch_id", "branchFeature"."updated_at" AS "branchFeature_updated_at", "branchFeature"."created_at" AS "branchFeature_created_at", "branchFeature"."branch_id" AS "branchFeature_branch_id", "branchFeature"."feature_id" AS "branchFeature_feature_id", "features"."id" AS "features_id", "features"."created_at" AS "features_created_at", "features"."name" AS "features_name", "features"."slug" AS "features_slug", "features"."updated_at" AS "features_updated_at" FROM "public"."branches" "branches" INNER JOIN "public"."branch_schedules" "branch_schedules" ON "branch_schedules"."branch_id"="branches"."id" AND ("branch_schedules"."branch_id" = "branches"."id")  LEFT JOIN "public"."branches_features" "branchFeature" ON "branchFeature"."branch_id"="branches"."id" AND ("branchFeature"."branch_id" = "branches"."id")  LEFT JOIN "public"."features" "features" ON "features"."id"="branchFeature"."feature_id" ORDER BY branches.is_all_day DESC, branch_schedules.end_time::time DESC, "branch_schedules"."day" DESC, (case when "branch_schedules"."day" = 'holiday' then 1
                       when "branch_schedules"."day" = 'sunday' then 2
                       when "branch_schedules"."day" = 'saturday' then 3
                       when "branch_schedules"."day" = 'weekday' then 4
                       end) ASC, branch_schedules.start_time::time ASC LIMIT 5

But, through TypeORM, it retrieves a single result.
If I take the generated SQL and execute it on the database, I get the 5 requested rows.

If I use .execute() instead of getMany() I get the 5 requested rows.

I have another (working) entity using the same queryBuilder query, but without relations.

If this is not a bug and there is more to limit() please link me to the correct part of the docs.

Activity

  1. Kononnable commented on Apr 20, 2019

    @Kononnable
    Contributor

    If you use execute or run generated query in DB - does results are distinct from each other, or is it same row but returned five times?

  2. cuni0716 commented on Jun 8, 2019

    @cuni0716

    the same row returned N times

  3. chrislgrigg commented on Jun 14, 2019

    @chrislgrigg

    I think I'm seeing the same thing. Given a similar query with three calls to leftJoinAndSelect and a limit(30), I'll get fewer than the requested rows when using getMany() and the correct number using execute(). The two queries generated are identical.

    Looking at getRawAndEntities, I see clearly that it is returning 30 rows: one for each of one of the joined rows, which is a OneToMany association. A second query was my solution.

        const paginatedFilter = associatedQuery.offset(currentPage * 30).limit(30);
        const exerciseSeries = await paginatedFilter.orderBy('series.created_at', 'DESC').getMany();
        const results = await getRepository(ExerciseResult).find({ where: { exerciseSeriesId: In(exerciseSeries.map(s => s.id)) } });
        exerciseSeries.forEach(s => {
          s.exerciseResults = results.filter(r => r.exerciseSeriesId === s.id);
        });

    I felt like leftJoinAndMapMany should have been the right way to do this but I couldn't get it working. Would love it if there was a less hacky way.

  4. alitsvin commented on Sep 9, 2019

    @alitsvin

    typeorm has a small tip in documentation about situation when you want to get limited amount of entities with many relations. They advice to use .take(count) instead of .limit(count). I had similar issue and it helped.

  5. chrislgrigg commented on Sep 9, 2019

    @chrislgrigg

    @alitsvin Could you link to the relevant section of the docs?

  6. andreechristian commented on Jan 13, 2020

    @andreechristian

    I used skip and take, it wasn't working as expected :(

  7. Bat-Orshikh commented on Jan 30, 2020

    @Bat-Orshikh

    @andreechristian I have same problem here using take method with left join. Did you resolve your problem?

    I used take(6) with left join but it doesn't return 6 rows from left tables. take method influenced second table rows.

    I can proof that left table has more than 6 rows.

  8. milkstork-kevin commented on Mar 4, 2020

    @milkstork-kevin

    I want to confirm that I'm also seeing this bug. I have several leftJoins returning all of the rows exactly as I intend. But as soon as I add a .take(5), it returns all of my top-level fields correctly, but none of the child fields get selected. For example:

    Without .take

      [
          {
            "id": 486,
            "notes": "",
            "orderItems": [
              {
                "productId": 1,
                "product": {
                  "id": 1,
                  "location": "domestic"
                }
              },
              {
                "productId": 2,
                "product": {
                  "id": 2,
                  "location": "domestic"
                }
              }
        ]
    ]

    With .take

      [
          {
            "id": 486,
            "notes": "",
            "orderItems": []
          }
      ]
  9. ardyfeb commented on Apr 23, 2020

    @ardyfeb

    using .take() is expensive, typeorm will fetch entity id first, then generating real query and map first query results ids to IN query

  10. nimit95 commented on Nov 1, 2020

    @nimit95

    Yeah with postgres same is happening, with take it is generating an IN query, while with limit join query seems fine.

  11. IonVillarreal commented on Apr 2, 2022

    @IonVillarreal

    same problem here, it only happens in Postgres ?

  12. ab958 commented on Jul 12, 2023

    @ab958

    To get first 10 users with their photos.

    const users = await dataSource .getRepository(User) .createQueryBuilder("user") .leftJoinAndSelect("user.photos", "photo") .skip(10) .getMany()

    this query works but how to to get first 10 users with first 10 photos ?

  13. srosama commented on Apr 30, 2025

    @srosama

    The take and skip don't work with joins

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions