question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Where on association + limit throws db error

See original GitHub issue

I am experiencing the following issue. I am trying to execute the following query:

transaction.findAll({
            where: {
                '$tenant.privileges.user_pkey$': {
                    $eq: userPkey
                }
            },
            include: [
                {
                    model: this.account,
                    as: 'tenant',
                    attributes: [],
                    include: [
                        {
                            model: this.privilege,
                            as: 'privileges',
                            attributes: []
                        }
                    ]
                }
            ],
            order: 'transactionPkey',
            limit: 10
        });

I was expecting that I would get the top 10 transactions which fit the where clause.

However, instead I get a db error: missing FROM-clause entry for table "tenant.privileges"

The actual SQL produced is this:

SELECT “Transaction”.* FROM (SELECT “Transaction”.“transaction_pkey” AS “transactionPkey”, “Transaction”.“global_transaction_pkey” AS “globalTransactionPkey”, “Transaction”.“tenant_pkey” AS “tenantPkey”, “Transaction”.“tenant_name” AS “tenantName”, “Transaction”.“counterparty_pkey” AS “counterpartyPkey”, “Transaction”.“counterparty_name” AS “counterpartyName”, “Transaction”.“transaction_direction_pkey” AS “transactionDirectionPkey”, “Transaction”.“transaction_direction_name” AS “transactionDirectionName”, “Transaction”.“transaction_status_pkey” AS “transactionStatusPkey”, “Transaction”.“transaction_status_name” AS “transactionStatusName”, “Transaction”.“transaction_type_pkey” AS “transactionTypePkey”, “Transaction”.“transaction_type_name” AS “transactionTypeName”, “Transaction”.“transaction_timestamp” AS “transactionTimestamp”, “Transaction”.“gross_quantity” AS “grossQuantity”, “Transaction”.“tare_quantity” AS “tareQuantity”, “Transaction”.“seal_identifier” AS “sealIdentifier”, “Transaction”.“vehicle_identifier” AS “vehicleIdentifier”, “Transaction”.“note”, “Transaction”.“image_path” AS “imagePath” FROM “v_transaction” AS “Transaction” WHERE (“tenant.privileges”.“user_pkey” = 158) ORDER BY “Transaction”.“transaction_pkey” asc LIMIT ‘10’ OFFSET ‘0’) AS “Transaction” LEFT OUTER JOIN “v_account” AS “tenant” ON “Transaction”.“tenantPkey” = “tenant”.“account_pkey” LEFT OUTER JOIN “v_privilege” AS “tenant.privileges” ON “tenant”.“account_pkey” = “tenant.privileges”.“account_pkey” ORDER BY “Transaction”.“transactionPkey” asc;

I believe this error is occuring because the where clause is in the inner subquery while the joins are done in the outer query.

Is there any way to have it all get executed as one query as opposed to putting the joins in the outer query and all other stuff (where, limit etc.) in the inner one?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:2
  • Comments:11 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
hazolskycommented, Nov 27, 2016

I guess this is a known issue since, at least, Feb 11 2015. See #3095

UPD: you can use this workaround: http://stackoverflow.com/questions/26021965/sequelize-with-nodejs-cant-join-tables-with-limit#comment48821718_26026326

0reactions
FrostBycommented, Nov 20, 2018

Any news about this bug? option.subQuery=false helped me, but what about a fix in the core? Error: sqlMessage: 'Unknown column \'odds.type_id\' in \'on clause\'', Code:

dev.Match.findAll({
    include: [
      {model: dev.Team, as: 'team1'},
      {model: dev.Team, as: 'team2'},
      dev.Tournament,
      {model: dev.Game, where: {name: 'dota'}},
      {
        model: dev.Odd,
        required: true,
        include: [
          dev.Platform,
          {
            model: dev.Type,
            where: {
              name: {
                [Sequelize.Op.in]: [
                  '1x2',
                  'Winner',
                  '1st map - winner',
                  '2nd map - winner',
                  '3rd map - winner'],
              },
            },
          }
          ],
      }],
    limit: 3,
    where: {
      updatedAt: {
        [Sequelize.Op.gte]: moment().
            subtract(30, 'minutes').
            utc().
            toDate(),
      },
      date: {
        [Sequelize.Op.gte]: moment().
            subtract(2, 'hour').
            utc().
            toDate(),
      },
    },
    order: [['date', 'ASC'], ['updatedAt', 'DESC'], ['createdAt', 'DESC']],
  })

SQL:

SELECT `match`.*,
       `team1`.`id`                 AS `team1.id`,
       `team1`.`name`               AS `team1.name`,
       `team1`.`logo`               AS `team1.logo`,
       `team1`.`createdAt`          AS `team1.createdAt`,
       `team1`.`updatedAt`          AS `team1.updatedAt`,
       `team2`.`id`                 AS `team2.id`,
       `team2`.`name`               AS `team2.name`,
       `team2`.`logo`               AS `team2.logo`,
       `team2`.`createdAt`          AS `team2.createdAt`,
       `team2`.`updatedAt`          AS `team2.updatedAt`,
       `tournament`.`id`            AS `tournament.id`,
       `tournament`.`name`          AS `tournament.name`,
       `tournament`.`logo`          AS `tournament.logo`,
       `tournament`.`createdAt`     AS `tournament.createdAt`,
       `tournament`.`updatedAt`     AS `tournament.updatedAt`,
       `odds`.`id`                  AS `odds.id`,
       `odds`.`type_id`             AS `odds.type_id`,
       `odds`.`platform_id`         AS `odds.platform_id`,
       `odds`.`match_id`            AS `odds.match_id`,
       `odds`.`odd_1`               AS `odds.odd1`,
       `odds`.`odd_2`               AS `odds.odd2`,
       `odds`.`odd_3`               AS `odds.odd3`,
       `odds`.`odd_1_title`         AS `odds.odd1Title`,
       `odds`.`odd_2_title`         AS `odds.odd2Title`,
       `odds`.`odd_3_title`         AS `odds.odd3Title`,
       `odds`.`processed`           AS `odds.processed`,
       `odds`.`createdAt`           AS `odds.createdAt`,
       `odds`.`updatedAt`           AS `odds.updatedAt`,
       `odds->platform`.`id`        AS `odds.platform.id`,
       `odds->platform`.`name`      AS `odds.platform.name`,
       `odds->platform`.`logo`      AS `odds.platform.logo`,
       `odds->platform`.`createdAt` AS `odds.platform.createdAt`,
       `odds->platform`.`updatedAt` AS `odds.platform.updatedAt`
FROM (SELECT `match`.`id`,
             `match`.`team_1_id`,
             `match`.`team_2_id`,
             `match`.`date`,
             `match`.`tournament_id`,
             `match`.`game_id`,
             `match`.`createdAt`,
             `match`.`updatedAt`,
             `game`.`id`              AS `game.id`,
             `game`.`name`            AS `game.name`,
             `game`.`logo`            AS `game.logo`,
             `game`.`createdAt`       AS `game.createdAt`,
             `game`.`updatedAt`       AS `game.updatedAt`,
             `odds->type`.`id`        AS `odds.type.id`,
             `odds->type`.`name`      AS `odds.type.name`,
             `odds->type`.`createdAt` AS `odds.type.createdAt`,
             `odds->type`.`updatedAt` AS `odds.type.updatedAt`
      FROM `matches` AS `match`
             INNER JOIN `games` AS `game` ON `match`.`game_id` = `game`.`id` AND `game`.`name` = 'dota'
             INNER JOIN `types` AS `odds->type` ON `odds`.`type_id` = `odds->type`.`id` AND `odds->type`.`name` IN (
              '1x2',
              'Winner',
              '1st map - winner',
              '2nd map - winner',
              '3rd map - winner')
      WHERE `match`.`updatedAt` >= '2018-11-20 15:36:01'
        AND `match`.`date` >= '2018-11-20 14:06:01'
        AND (SELECT `odds`.`match_id`
             FROM `odds` AS `odds`
                    INNER JOIN `types` AS `type` ON `odds`.`type_id` = `type`.`id` AND `type`.`name` IN ('1x2',
                                                                                                         'Winner',
                                                                                                         '1st map - winner',
                                                                                                         '2nd map - winner',
                                                                                                         '3rd map - winner')
             WHERE (`odds`.`match_id` = `match`.`id`)
             LIMIT 1) IS NOT NULL
      ORDER BY `match`.`date` ASC, `match`.`updatedAt` DESC, `match`.`createdAt` DESC
      LIMIT 3) AS `match`
       LEFT OUTER JOIN `teams` AS `team1` ON `match`.`team_1_id` = `team1`.`id`
       LEFT OUTER JOIN `teams` AS `team2` ON `match`.`team_2_id` = `team2`.`id`
       LEFT OUTER JOIN `tournaments` AS `tournament` ON `match`.`tournament_id` = `tournament`.`id`
       INNER JOIN `odds` AS `odds` ON `match`.`id` = `odds`.`match_id`
       LEFT OUTER JOIN `platforms` AS `odds->platform` ON `odds`.`platform_id` = `odds->platform`.`id`
ORDER BY `match`.`date` ASC, `match`.`updatedAt` DESC, `match`.`createdAt` DESC;
Read more comments on GitHub >

github_iconTop Results From Across the Web

Unexpected SQL when including associations with a limit #5230
Hi, I want to query for a set of "Substances" based on their associations. I also want to paginate the results of this...
Read more >
Database Engine events and errors - SQL Server
Consult this MSSQL error code list to find explanations for error messages for SQL Server database engine events.
Read more >
associations - Cakephp Passing Conditions to Contain throws ...
Check for example How to limit contained associations per ... Cookbook > Database Access & ORM > Query Builder > Loading Associations ......
Read more >
Kill N+1 Queries For Good with Strict Loading - Matt Sears
Starting with Rails 6.1, we can set a strict_loading configuration option that, when true , will throw an error if your code attempts...
Read more >
Active Record Associations - Rails Edge Guides
Active Record AssociationsThis guide covers the association features of Active Record.After reading this guide, you will know: How to declare associations ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found