Skip to content

$association.references$ are incompatible with limit and one-to-many & many-to-many includes/associations #12971

Open

Description

@apresmoi

Issue Description

What are you doing?

I'm trying to run the queries shown here adding the limit parameter on the top level.

I've created a small Codesandbox using the examples on the documentation and adding the limit parameter. The resulting query can be easily seen in the sandbox console.

Here is the query anyway:

User.findAll({
    where: {
      "$Instruments.id$": { [Sequelize.Op.is]: null }
    },
    include: {
      model: Tool,
      as: "Instruments"
    },
    limit: 2
  }).catch((err) => {});

What do you expect to happen?

SELECT `user`.*,
    `Instruments`.`id` AS `Instruments.id`,
    `Instruments`.`name` AS `Instruments.name`,
    `Instruments`.`size` AS `Instruments.size`,
    `Instruments`.`userId` AS `Instruments.userId`
FROM (
        SELECT `user`.`id`,
            `user`.`name`
        FROM `users` AS `user`
    ) AS `user`
    LEFT OUTER JOIN `tools` AS `Instruments` ON `user`.`id` = `Instruments`.`userId`
WHERE `Instruments`.`id` IS NULL
LIMIT 2

What is actually happening?

SELECT `user`.*,
    `Instruments`.`id` AS `Instruments.id`,
    `Instruments`.`name` AS `Instruments.name`,
    `Instruments`.`size` AS `Instruments.size`,
    `Instruments`.`userId` AS `Instruments.userId`
FROM (
        SELECT `user`.`id`,
            `user`.`name`
        FROM `users` AS `user`
        WHERE `Instruments`.`id` IS NULL
        LIMIT 2
    ) AS `user`
    LEFT OUTER JOIN `tools` AS `Instruments` ON `user`.`id` = `Instruments`.`userId`

Additional context

I believe the queries and the code explain themselves. What I'm trying to achieve is that exact query:

  1. Be able to do a LEFT OUTER
  2. Filter it by the missing matches (ie "id" is NULL)
  3. Limit the query.

If there is any other way to manage to obtain the query that I expect feel free to suggest it !

Environment

  • Sequelize version: 6.4.0
  • Node.js version: 10.22.0
  • Operating System: macOS / Codesandbox is running a regular linux

Issue Template Checklist

How does this problem relate to dialects?

  • I think this problem happens regardless of the dialect.
  • I think this problem happens only for the following dialect(s):
  • I don't know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Regards

Activity

  1. github-actions commented on Oct 27, 2021

    @github-actions
  2. MCD-50 commented on Nov 5, 2021

    @MCD-50

    Are there any updated on this?

  3. bernardmma commented on Nov 8, 2021

    @bernardmma

    I just encountered this as well. Any ideas?

  4. abhiburk commented on Jan 18, 2022

    @abhiburk

    When using limit and offset Unknown column in ............ where clause

  5. added
    type: bug
    and removed on Jan 19, 2022
  6. ephys commented on Jan 19, 2022

    @ephys
    Member

    Adding limit turns the query into a subQuery to ensure limit only impacts how many users are returned.

    Adding subQuery: false could solve your issue, with a caveat, but this is indeed a bug as even when using a subQuery, $references$ to joined tables should still function.

  7. reopened this on Jan 19, 2022
  8. ephys commented on Mar 18, 2022

    @ephys
  9. 6 remaining items

  10. carsonweinand commented on Mar 28, 2022

    @carsonweinand

    FYI for my specific use case I need to apply filter criteria across multiple associated models --> for example, check if price falls within a certain range on table abc OR table xyz.

    This is why I am using the $association.reference$ syntax because I don't know how to perform the action I just mentioned with using include: [{model: Model}, where: {}]

    $association.reference$ allows me to include table abc and table xyz and return results that apply to either / or.

  11. Taqiarzoo commented on Mar 29, 2022

    @Taqiarzoo

    .
    `order.findAll({

    include: [{
        model: invoice,
    },
    {
        model: peoducts,
        attributes:['id','item_no','name','item_price','item_src']
    }],
    where: {
        //Apply filter on parent table
        [Op.and]: [{
            oredr_date: {
                [Op.between]: [order_date_min, order_date_max]
            },
            //apply filter on assoiciate tables
            '$invoice.price$': {
                [Op.between]: [price_min, price_max]
            },
        }],
    },
    subQuery: false,
    offset: page,
    limit: limit,
    group: ['id']
    

    })`

    this will return all data but only single record from has_many relations

  12. ephys commented on Mar 29, 2022

    @ephys
    Member

    @carsonweinand Your use case is the exact one that would really benefit from supporting this syntax in subQueries. That unfortunately means that right now your only option is to write a raw query.
    If you manage to come up with one, don't hesitate to share its details. It would help us resolve this issue

  13. carsonweinand commented on Mar 29, 2022

    @carsonweinand

    @ephys I have one other issue... I am trying to get the count of associated bids and offers but those added attributes don't appear in the output unless I include "raw: true" (but raw: true adds extra results and is incorrect for my use case). My query is below. Do you know why "BidCount" and "OfferCount" don't appear as attributes?

    const listingResultsQuery = {
    where: listingFilters,
    // limit: 25, // when adding a limit it throws error: "missing FROM-clause entry for 'table'"
    distinct: true, // used for total count
    offset: parseInt(query.offset[0]),
    order: sortByQuery(query.sortby ? query.sortby[0] : null),
    attributes: [
    "id",
    "title",
    "createdAt",
    [
    Sequelize.literal(
    "(SELECT COUNT() FROM Offer WHERE Offer.listingId = Listing.id)"
    ),
    "OfferCount",
    ],
    [
    Sequelize.literal(
    "(SELECT COUNT(
    ) FROM Bid WHERE Bid.listingId = Listing.id)"
    ),
    "BidCount",
    ],
    ],
    };

    const listingResults = await Models.Listings.findAndCountAll(
    listingResultsQuery
    );

  14. sreeenivasyadav commented on Apr 19, 2022

    @sreeenivasyadav
  15. ephys commented on May 17, 2022

    @ephys
    Member

    I think I figured out a way to solve this

    To sum things up:

    The issue

    When using limit and include in the same query, the expected behavior is that each limit only applies to the model it's added to. The following query:

    User.findAll({
      include: [{
        association: 'projects',
      }],
      limit: 2,
    });

    Should return up to two users, each with up to 10 projects.

    Right now, Sequelize wraps User in a subQuery to make sure limit: 2 only applies to User, not projects. Which results in (roughly) this:

    SELECT u.*
    FROM (SELECT * FROM users LIMIT 2) u
    LEFT JOIN projects p ON u.id = p.user_id;

    This query breaks down if we try to filter using the association:

    User.findAll({
      include: [{
        association: 'projects',
      }],
      limit: 2,
      where: { '$project.id$': null }
    });

    results in

    SELECT users.*
    FROM (
      SELECT * FROM users 
      WHERE projects.id IS NULL -- OH NO!
      LIMIT 2
    ) users
    LEFT JOIN projects ON users.id = projects.user_id;

    First solution (fast)

    if the check being done is 'the association does not exist', we don't need to use a subQuery. We should revert back to a regular query for this scenario.

    The generated SQL for that query should be:

    SELECT users.*
    FROM SELECT * FROM users
    LEFT JOIN projects ON users.id = projects.user_id
    WHERE projects.id IS NULL
    LIMIT 2;

    More general solution (slow)

    By using PARTITION BY, we can build a query that is capable of filtering using associations.

    SELECT * FROM (
      SELECT
        *,
        row_number() OVER (PARTITION BY user_row) AS row
      FROM (
        SELECT
          users.id as uid, users.name as uname,
          projects.id as pid, projects.name as pname,
          row_number() OVER (PARTITION BY users.id) AS user_row FROM users
        LEFT JOIN projects projects on users.id = projects.user_id
        WHERE projects.id IS NULL
      ) rows
    ) rows
    -- 'limit: 2' on user
    WHERE rows.row <= 2;

    Caveats:

    • The above requires two levels of PARTITION because I need to assign a unique value to each user, without gaps. If someone knows of a better way to do this, this could be even more efficient.
    • This query is much more expensive, but it can be used as a last-resort if the simpler queries we support are not sufficient. (in order of complexity: no subquery -> subquery on main table -> this partition query).
    • Right now my example only handles limit at the top level. Still need to determine how a limit can be set for each include.
    • The initial issue does not actually need to use a subQuery, and using this monstrous query would be redundant.
    • It's unlikely I'll implement any of this before all queryGenerators have been migrated to TypeScript, due to the sheer complexity of all of this.

    TO DO

    • Check whether there is a way to remove one of the partitions
    • Figure out how to have separate limit on each include.
    • Implement the complex nested partition.
    • Make sure the 'no subquery' version of OP's query is used when the only check being done is "model has no association"
    • Remove the subQuery and duplicating options, replace them with queryStyle: 'simple' | 'subQuery' | 'partitionned'
  16. nikkorfed commented on May 24, 2022

    @nikkorfed

    Hi everyone! It seems that there's another way of building a query that is capable of filtering by associations (without partitions).

    Using OP's example, for getting 5 users with the instrument's size large the SQL-query would be like:

    SELECT user.*, instruments.*
    FROM users AS user
    LEFT OUTER JOIN tools AS instruments
    ON user.id = instruments.userId
    WHERE user.id IN (
        SELECT DISTINCT user.id
        FROM users AS user
        LEFT OUTER JOIN tools AS instruments
        ON user.id = instruments.userId
        WHERE instruments.size = 'large'
        LIMIT 5
    )

    The main idea here is that there is a subquery, which is executed with desired WHERE, LIMIT and JOIN clauses, but with DISTINCT 'id' also. This produces the list of IDs that satisfies our query (users filtered by joined instruments' size) and the number of IDs in that list is limited to 5.

    This array of IDs is then used in WHERE clause for the main query. It retrieves all the users with these IDs and joins required associations to them, sets some order, etc. In the end, we just receive specified number of users filtered by some nested attribute.

    So the combination of DISTINCT 'id' and LIMIT in a subquery behaves like imaginary LIMIT ON (id) 5, which says "limit the number of records to keep only 5 unique IDs (instead of rows)".

    Hope this'll help with resolving the issue. Please, let me know if missed something.

  17. nikkorfed commented on May 25, 2022

    @nikkorfed

    In addition to the above, to limit the number of associations for each include (@ephys's question) , JOIN in the main query needs a few adjustments. Instead of regular LEFT OUTER JOIN tools AS instruments ON user.id = instruments.userId there should be:

    LEFT OUTER JOIN (
        SELECT *, row_number() OVER (PARTITION BY tools.userId) AS row
        FROM tools 
    ) AS instruments
    ON user.id = instruments.userId AND instruments.row <= 3

    This JOIN basically divides associated tools into partitions (for each user), numerates them in row column and then joins only the ones that are numerated up to 3. As a result, we receive up to 3 tools for each user.

  18. verstoff commented on Sep 6, 2022

    @verstoff

    Ok, guys, here is some proof-of-concept workaround inspired by @nikkorfed idea.

    ModelClass.addHook('beforeFindAfterOptions', async (optionsArg) => {
        // Custom options for alternative limit (altLimit) and offset (altOffset)
        let { altLimit, altOffset } = optionsArg
        if (!altLimit && !altOffset) {
          return;
        }
    
        const defaultOptions = {
          ...optionsArg, type: sequelize.QueryTypes.SELECT, model: ModelClass
        }
        
        let subQuerySQL = sequelize.getQueryInterface().queryGenerator.selectQuery(ModelClass.getTableName(), {
          ...defaultOptions,
          group: ModelClass.primaryKeyAttribute,
          limit: altLimit,
          offset: altOffset,
          subQuery: false
        }, ModelClass).replace(/;$/, '')
    
        const primaryKey = `\`${ModelClass.name}\`.\`${ModelClass.primaryKeyAttribute}\``
        
        const inQuery = 'SELECT DISTINCT `tmp`.`' + ModelClass.primaryKeyAttribute + '` FROM (' + subQuerySQL +  ') `tmp`'
        const whereLiteral = primaryKey + ' IN (' + inQuery + ')'
        optionsArg.where = {
          [Sequelize.Op.and]: [
            optionsArg.where,
            Sequelize.literal(whereLiteral)
          ]
        }
      })
  19. sdesbiens commented on Jan 12, 2024

    @sdesbiens

    I'm having this issue as well, but I'm wondering if the general SQL structure that's being generated today couldn't be preserved. In my particular example it seems like if the association appears in the main where clause with the $association.field$ sort of style, then the table for that association in the SQL could also be duplicated within the limit subquery from:

    SELECT `user`.*,
        `Instruments`.`id` AS `Instruments.id`,
        `Instruments`.`name` AS `Instruments.name`,
        `Instruments`.`size` AS `Instruments.size`,
        `Instruments`.`userId` AS `Instruments.userId`
    FROM (
            SELECT `user`.`id`,
                `user`.`name`
            FROM `users` AS `user`
            WHERE `Instruments`.`id` IS NULL
            LIMIT 2
        ) AS `user`
        LEFT OUTER JOIN `tools` AS `Instruments` ON `user`.`id` = `Instruments`.`userId`
    

    To something like:

    SELECT `user`.*,
        `Instruments`.`id` AS `Instruments.id`,
        `Instruments`.`name` AS `Instruments.name`,
        `Instruments`.`size` AS `Instruments.size`,
        `Instruments`.`userId` AS `Instruments.userId`
    FROM (
            SELECT DISTINCT `user`.`id`,
                `user`.`name`
            FROM `users` AS `user`
               LEFT OUTER JOIN `tools` AS `Instruments` ON `user`.`id` = `Instruments`.`userId`
            WHERE `Instruments`.`id` IS NULL
            LIMIT 2
        ) AS `user`
        LEFT OUTER JOIN `tools` AS `Instruments` ON `user`.`id` = `Instruments`.`userId`
    WHERE `Instruments`.`id` IS NULL
    

    Adding DISTINCT to the Sub query which limits the results to only the fields of the model that's being queried on so you can join other associations that appear in the main WHERE clause without affecting the rows, and then you add the WHERE clause to the outer most part of the query again to filter on those aspects when joining to that table again for the final results.

    I was working with Postgres in my example, and had an ORDER BY part, which also requires some care when adding the DISTINCT to the subquery since I specifically added COLLATE "C" to the Sequelize query order which caused me to have to add that expression to the SELECT list of the subquery.

    Would that not work?

  20. kurokeita commented on Nov 29, 2024

    @kurokeita

    Hi, is there any update on this? I'm encountering this issue at the moment with complex top level clauses. Querying with limit does not get all the associations. What I'm doing at the moment is query with complex conditions first to get the ids then do another query where id in (*) to get the full data.

  21. caseyt commented on Jan 10, 2025

    @caseyt
  22. caseyt commented on Jan 10, 2025

    @caseyt
  23. added theissue type on Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: bug

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions