Skip to content

Combination of INNER JOIN and LEFT OUTER JOIN with LIMIT (ORDER BY) #2145

Closed

Description

@ThePoloQ

Hi,

Sequelize version 1.7

I think there is a problem with the query generation when there is a combinaison of INNER JOIN and LEFT OUTER JOIN with LIMIT

Here the illustration:

var options = {
  include:  [ {model: db.User, as: 'Responsible', attributes: ['username'], required: true},
              {model: db.Application, as: 'Application', attributes: ['name'], required: true},
              {model: db.Subtask, as: 'Subtasks', attributes: ['ended', 'title']},
              {model: db.State, as: 'State', attributes: ['title','type'], where: {isTerminate:  true}, required: true}],
  offset:   db.limit*(req.params.pageid-1),
  limit:    db.limit,
  order:    [ [db.sequelize.fn('datetime', db.sequelize.col('Tasks.endedAt')), 'DESC'],
              // 2 Lines below are bugged
              //[{model: db.Application, as: 'Application'}, 'name']
              //[db.sequelize.fn('lower',db.sequelize.col('Subtasks.title'))]
              ]
}
db.Task.findAndCountAll(options).success(function(result) {...});

Here the query

SELECT 
  `Tasks`.*, `Subtasks`.`ended` AS `Subtasks.ended`, 
  `Subtasks`.`title` AS `Subtasks.title`, 
  `Subtasks`.`id` AS `Subtasks.id` 
FROM 
  (SELECT 
    `Tasks`.*, `Responsible`.`username` AS `Responsible.username`, 
    `Responsible`.`id` AS `Responsible.id`, 
    `Application`.`nom` AS `Application.name`, 
    `Application`.`id` AS `Application.id`, 
    `State`.`title` AS `State.title`, 
    `State`.`type` AS `State.type`, 
    `State`.`id` AS `State.id` 
  FROM `Tasks` 
  INNER JOIN `Users` AS `Responsible` ON `Responsible`.`id` = `Tasks`.`UserId` 
  INNER JOIN `Applications` AS `Application` ON `Application`.`id` = `Tasks`.`ApplicationId` 
  INNER JOIN `States` AS `State` 
    ON `State`.`id` = `Tasks`.`StateId` 
    AND `State`.`isTerminate`=1   
  ORDER BY datetime(`Tasks`.`endedAt`) DESC, lower(`Subtasks`.`title`) LIMIT 20
  ) AS `Tasks` 
LEFT OUTER JOIN `Subtasks` AS `Subtasks` 
  ON `Tasks`.`id` = `Subtasks`.`TaskId` 
ORDER BY datetime(`Tasks`.`endedAt`) DESC, `Application`.`name`, lower(`Subtasks`.`title`);

we can see how SELECT .. FROM and in the second Subtasks are not yet selected

EDIT The expected query : not really see below comments

SELECT 
  `Tasks`.*, `Responsible`.`username` AS `Responsible.username`, 
  `Responsible`.`id` AS `Responsible.id`, 
  `Application`.`name` AS `Application.name`, 
  `Application`.`id` AS `Application.id`, 
  `State`.`title` AS `State.title`, 
  `State`.`type` AS `State.type`, 
  `State`.`id` AS `State.id` 
FROM `Tasks` 
INNER JOIN `Users` AS `Responsible` ON `Responsible`.`id` = `Tasks`.`UserId` 
INNER JOIN `Applications` AS `Application` ON `Application`.`id` = `Tasks`.`ApplicationId` 
INNER JOIN `States` AS `State` 
    ON `State`.`id` = `Tasks`.`StateId` 
    AND `State`.`isTerminate`=1 
LEFT OUTER JOIN `Subtasks` AS `Subtasks` ON `Tasks`.`id` = `Subtasks`.`TaskId` 
ORDER BY datetime(`Tasks`.`datefin`) DESC, `Application`.`name`, lower(`Subtasks`.`title`)
LIMIT 20;

Below the SQL error

no such column: Subtasks.title

That's why i think there are troubles in query generation.

Can you fix it ?

Thanks

Activity

  1. janmeier commented on Aug 13, 2014

    @janmeier
    Member

    Could you please post your models and associations

  2. ThePoloQ commented on Aug 13, 2014

    @ThePoloQ
    Author

    Thanks for your reply

    Below my models

    var Sequelize = require('sequelize')
    
     var myDB = new Sequelize('database', 'username', 'password', {
      dialect: 'sqlite',
      storage: process.env.DATABASEPATH
      });
    
    var User = myDB.define('User', {
        username: {type: Sequelize.STRING,, unique: true, allowNull: false},
        passwordHASH: {type: Sequelize.STRING, allowNull: false},
        isAdmin: {type: Sequelize.BOOLEAN, defaultValue: false},
      },
      {
        timestamps: false,
      });
    
    var Task = myDB.define('Task', {
        title: {type: Sequelize.STRING, allowNull: false},
        ticket: Sequelize.STRING,
        description: Sequelize.TEXT,
        endeAt: Sequelize.DATE
      },
      {
        timestamps: true,
      }
    );
    
    var Subtask = myDB.define('Subtask', {
      title: {type: Sequelize.STRING, allowNull: false},
      ticket: Sequelize.STRING,
      ended: {type: Sequelize.BOOLEAN, defaultValue: false},
      },
      {
        timestamps: false,
        getterMethods: {
          text: function () {
              return [this.ended ? '[X]' : '[ ]', this.title].join(' ');
          }
        }
      });
    
    var State = myDB.define('State', {
      title: {type: Sequelize.STRING, allowNull: false},
      isTerminate: {type: Sequelize.BOOLEAN, defaultValue: false},
      weight: {type: Sequelize.INTEGER, defaultValue: 0},
      type: {type: Sequelize.STRING, defaultValue: "default"},
      },
      {
        timestamps: false,
      });
    
    var Application = myDB.define('Application', {
      name: {type: Sequelize.STRING, allowNull: false},
      infos: {type: Sequelize.TEXT},
      weight: {type: Sequelize.INTEGER, defaultValue: 0},
      color: {type: Sequelize.STRING, defaultValue: "grey"},
      },
      {
        timestamps: false,
      });
    
    Task.belongsTo(User, { as: 'Responsible' })
    User.hasMany(Task, { as: 'Tasks' })
    
    Task.belongsTo(State, { as: 'State' })
    Etat.hasMany(Task, { as: 'Tasks' })
    
    Task.belongsTo(Application, { as: 'Application' })
    Application.hasMany(Task, { as: 'Tasks' })
    
    Subtask.belongsTo(Task, { as: 'Task', foreignKey: 'TaskId' })
    Task.hasMany(Subtask, { as: 'Subtasks', foreignKey: 'TaskId' })

    To help you without limit it works fine, example:

    var options = {include: [   {model:db.User, as: 'Responsible', attributes: ['username'], required: true},
                                {model: db.Subtask, as: 'Subtasks', attributes: ['ended', 'title']},
                                {model: db.Application, as: 'Application', attributes: ['name'], required: true},
                                {model: db.State, as: 'State', attributes: ['title','type'], where: {isTerminate:  false}, required: true}],
                      order: [[{model: db.State, as: 'State'}, 'weight'],
                              [{model: db.State, as: 'State'}, 'title'],
                              [{model: db.Application, as: 'Application'}, 'weight'],
                              [{model: db.Application, as: 'Application'}, 'name'],
                              [db.sequelize.fn('datetime', db.sequelize.col('Tasks.updatedAt')), 'DESC'],
                              [db.sequelize.fn('lower',db.sequelize.col('Subtasks.title'))]]
                    }
    options.where = {};
    
    if (req.params.appid){
      options.where.ApplicationId = req.params.appid;
    }
    if (req.params.stateid){
      options.where.StateId = req.params.stateid;
    }
    
    db.Task.findAll(options).success(function(tasks) { ... });

    The generated query :

    SELECT `Tasks`.*, `Responsible`.`username` AS `Responsible.username`, `Responsible`.`id` AS `Responsible.id`, `Subtasks`.`ended` AS `Subtasks.ended`, `Subtasks`.`title` AS `Subtasks.title`, `Subtasks`.`id` AS `Subtasks.id`, `Application`.`name` AS `Application.name`, `Application`.`id` AS `Application.id`,`State`.`title` AS `State.title`, `State`.`type` AS `State.type`, `State`.`id` AS `State.id` FROM `Tasks` INNER JOIN `Users` AS `Responsible` ON `Responsible`.`id` = `Tasks`.`UserId` LEFT OUTER JOIN `Subtasks` AS `Subtasks` ON `Tasks`.`id` = `Subtasks`.`TaskId` INNER JOIN `Applications` AS `Application` ON `Application`.`id` = `Tasks`.`ApplicationId` INNER JOIN `States` AS `State` ON `State`.`id` = `Tasks`.`StateId` AND `State`.`isTerminate`=0 WHERE 1=1 ORDER BY `State`.`weight`, `State`.`title`, `Application`.`weight`, `Application`.`name`, datetime(`Tasks`.`updatedAt`) DESC, lower(`Subtasks`.`title`);
  3. redexp commented on Aug 13, 2014

    @redexp

    Same problem

    If I set limit option then I expect that limit will be set in the end of sql query, but sudenly it creates subQuery with limit in it. It heppens when I have hasMany relation like Compnay.hasMany(Client) and I make query with included Client and with limit like

    var query = {
      include: [Client],
      where: ['clients.name = ?', clientName],
      limit: 10
    }
    
    Company.findAll(query)

    this creates sql like

    select ... from (select ... from company where clients.name = '...' limit 10) as company join client as clients on ...
    

    but I expected

    select ... from company join client as clients on ... where clients.name = '...' limit 10
    
  4. ThePoloQ commented on Aug 18, 2014

    @ThePoloQ
    Author

    It is a bit crippling. Have you got any possible solution ?

  5. janmeier commented on Aug 18, 2014

    @janmeier
    Member

    @redexp @mickhansen knows this stuff better than me, but I'm pretty sure that query is correct, in that it will limit you to 10 companies. If you place the limit at the end of the query it will limit the number of joined rows instead. Suppose company 42 has 3 clients, 1, 2 and 3. That will generate the following joined rows:

    company_id client_id
    42 1
    42 2
    42 3

    That means that company will be counted 3 times in the limit. Therefore we find 10 matching companies first (with the inner query) and then join them with the matching clients

  6. ThePoloQ commented on Aug 18, 2014

    @ThePoloQ
    Author

    The problem here, i think, it is the ORDER BY. It tried to order in the second select with entities from the first select (left join). And INNER + LEFT have to generate two selects, it is correct for me.
    As you said the LIMIT after INNER JOINs it is correct too.

    Do you agree ?

  7. janmeier commented on Aug 18, 2014

    @janmeier
    Member

    Have you tried putting the order for subtask.title inside the include?

    {
      model: db.Subtask, 
      as: 'Subtasks', 
      attributes: ['ended', 'title'],
      order: [db.sequelize.fn('lower',db.sequelize.col('Subtasks.title'))]
    }
  8. ThePoloQ commented on Aug 18, 2014

    @ThePoloQ
    Author

    For me it will be ignored. Because when i read API, you can't do that.

    {
    model:
    as:
    where:
    attributes:
    required:
    include: {}
    }

    https://github.com/sequelize/sequelize/wiki/API-Reference-Model#findAll

    I tried and it is ignored.

  9. mickhansen commented on Aug 18, 2014

    @mickhansen
    Contributor

    There is no order support for include (as of yet, limit/order support is on the list though). Placing limit on the outer query for :M row duplicating queries is obviously not possible (and not sure why people would expect that).

    Not all cases are supported unfortuneatly, we're constantly working on improving that. Pull requests with test cases are always welcome, fixes evenmore so.

  10. ThePoloQ commented on Aug 18, 2014

    @ThePoloQ
    Author

    Yes I understand for the LIMIT, and as i said this part is correctly generated.
    Can you help me saying in which part of sequelize library i have to search ? I can try a fix for multiple ORDER with combination of INNER and OUTER

  11. changed the title [-]Combinaison of INNER JOIN and LEFT OUTER JOIN with LIMIT[/-] [+]Combination of INNER JOIN and LEFT OUTER JOIN with LIMIT[/+] on Aug 18, 2014
  12. changed the title [-]Combination of INNER JOIN and LEFT OUTER JOIN with LIMIT[/-] [+]Combination of INNER JOIN and LEFT OUTER JOIN with LIMIT (ORDER BY)[/+] on Aug 18, 2014
  13. mickhansen commented on Aug 18, 2014

    @mickhansen
    Contributor

    https://github.com/sequelize/sequelize/blob/master/lib/dialects/abstract/query-generator.js#L686
    This is the method responsible for generating the select query.
    Even a PR with a simplified test case covering the issue/case would be helpfull :)

  14. mickhansen commented on Aug 18, 2014

    @mickhansen
    Contributor

    But yeah most likely it won't work correctly with subqueries and multiple orders (where some of those orders are on included tables).
    I'm not even sure how a query like that would look.

  15. ThePoloQ commented on Aug 19, 2014

    @ThePoloQ
    Author

    I'm not a SQL expert but I think the correct query with order is :

    SELECT 
      `Tasks`.*, `Subtasks`.`ended` AS `Subtasks.ended`, 
      `Subtasks`.`title` AS `Subtasks.title`, 
      `Subtasks`.`id` AS `Subtasks.id`
    FROM 
      (SELECT 
        `Tasks`.*,
        `Responsible`.`username` AS `Responsible.username`, 
        `Responsible`.`id` AS `Responsible.id`, 
        `Application`.`name` AS `Application.name`, 
        `Application`.`id` AS `Application.id`, 
        `State`.`title` AS `State.title`, 
        `State`.`type` AS `State.type`, 
        `State`.`id` AS `State.id` 
      FROM `Tasks` 
      INNER JOIN `Users` AS `Responsible` ON `Responsible`.`id` = `Tasks`.`UserId` 
      INNER JOIN `Applications` AS `Application` ON `Application`.`id` = `Tasks`.`ApplicationId` 
      INNER JOIN `States` AS `State` 
        ON `State`.`id` = `Tasks`.`StateId` 
        AND `State`.`isTerminate`=1
      ORDER BY datetime(`Tasks`.`endedAt`) DESC, `Application`.`name`
      LIMIT 20
      ) AS `Tasks` 
    LEFT OUTER JOIN `Subtasks` AS `Subtasks` 
      ON `Tasks`.`id` = `Subtasks`.`TaskId` 
    ORDER BY datetime(`Tasks`.`endedAt`) DESC, `Application.name`, lower(`Subtasks`.`title`);

    @mickhansen Do you agree with ?

    EDIT

  16. 22 remaining items

  17. felixfbecker commented on Oct 6, 2016

    @felixfbecker
    Contributor

    Then we should close the issue and remove the bug label?

  18. smfoote commented on Feb 25, 2017

    @smfoote

    I hope this will be helpful to someone. I was having the same issue as the original issue, but using v2.4. My query looked like this:

    Entry.findAll({
      where: {
        UserId: user.id
      },
      include: [{
        model: Topic,
        through: 'EntryTopic,
        attributes: ['name', 'id']
      }],
      offset: 1,
      limit: 10,
      order: 'date DESC'
    })
    

    The error for me was in the order statement. I changed it from 'date DESC' to [ [ 'date', 'DESC' ] ], and then the ordering began to work correctly. The docs warn against using the string version, but I didn't read them carefully enough.

  19. rajajlidi commented on Apr 11, 2017

    @rajajlidi

    i succeed in doing one inner join but when i want to to do double it don't work are there any help?

  20. stale commented on Jun 29, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  21. overlookmotel commented on Jun 29, 2017

    @overlookmotel
    Contributor

    Still may be an issue I think, Mr Robot.

  22. stale commented on Aug 28, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  23. abCods commented on Sep 22, 2017

    @abCods

    I am still facing the issue with following scenario.
    Client and InternalInquiry has 1:m relationship.

    When I include InternalInquiry as Join Table in where clause and put a limit to it. Sequelize produces sub-query due to limit which causes join table's column not being recognized.

    Here is my query.

    Client.findAll({ where: { $and: [{'$InternalInquiry.object_id$': params.project},
                                     {'$InternalInquiry.object_type$': 'project'}],
                              include: [{ model: sequelize.models.InternalInquiry,
                                          as: 'InternalInquiry',
                                          foreignKey: 'clientID',
                                          attributes: ['inquiry_id', 'object_id', 'object_type']}], 
                              limit:  15,
                              offset: 0 }})
    

    This is the generated SQL

    SELECT `Client`.*,
           `InternalInquiry`.`inquiry_id` AS `InternalInquiry.inquiry_id`,
           `InternalInquiry`.`object_id` AS `InternalInquiry.object_id`,
           `InternalInquiry`.`object_type` AS `InternalInquiry.object_type`
    FROM
      (SELECT `Client`.`clientid`,
              `Client`.`name`,
              `Client`.`phone`,
              `Client`.`cell`,
              `Client`.`fax`,
              `Client`.`email`
       FROM `clients` AS `Client`
       WHERE (`InternalInquiry`.`object_id` = '170'
              AND `InternalInquiry`.`object_type` = 'project')
       LIMIT 0,
             50) AS `Client`
    LEFT OUTER JOIN `zn_internal_inquiries` AS `InternalInquiry` ON `Client`.`clientid` = `InternalInquiry`.`clientID`;
    

    And the error I get is

    Unknown column 'InternalInquiry.object_id' in 'where clause'

  24. abCods commented on Sep 22, 2017

    @abCods

    I believe the issue has been closed but we know it persists and it is very critical for us as we are evaluating ORMs for our project and we don't want to rework the APIs.

  25. cuxs commented on Jan 22, 2018

    @cuxs

    This is still an issue! 😞

    This code

     const { Op } = sequelize;
            const options = {};
            args.text += '%';
            const LIMIT = 9;
    
            options.where = {
              [Op.and]: { carState: args.carState },
            };
    
            if (args.page) {
              options.limit = LIMIT;
              options.offset = args.page === 1 ? 0 : (args.page - 1) * LIMIT;
            }
            if (args.fuel) {
              options.where[Op.and] = Object.assign(options.where[Op.and], { fuel: args.fuel });
            }
            if (args.year) {
              options.where[Op.and] = Object.assign(options.where[Op.and], { year: args.year });
            }
            if (args.state) {
              options.include = [
                {
                  model: PublicationState,
                  where: {
                    stateName: args.state,
                  },
                }];
            }
               return Publication.findAndCountAll(options)
                    .then((publications) => {
                         result.Publications = publications.rows;
                         return result;
    }

    Returns this:

    count: 7,
      rows:
       [ Publication {
           dataValues: [Object],
           _previousDataValues: [Object],
           _changed: {},
           _modelOptions: [Object],
           _options: [Object],
           __eagerlyLoadedAssociations: [],
           isNewRecord: false,
           PublicationStates: [Array] },
         Publication {
           dataValues: [Object],
           _previousDataValues: [Object],
           _changed: {},
           _modelOptions: [Object],
           _options: [Object],
           __eagerlyLoadedAssociations: [],
           isNewRecord: false,
           PublicationStates: [Array] },
         Publication {
           dataValues: [Object],
           _previousDataValues: [Object],
           _changed: {},
           _modelOptions: [Object],
           _options: [Object],
           __eagerlyLoadedAssociations: [],
           isNewRecord: false,
           PublicationStates: [Array] },
         Publication {
           dataValues: [Object],
           _previousDataValues: [Object],
           _changed: {},
           _modelOptions: [Object],
           _options: [Object],
           __eagerlyLoadedAssociations: [],
           isNewRecord: false,
           PublicationStates: [Array] } ] }
    

    As you can see the number of results differs of the actual results that are being returned. And this is the generated query:

    SELECT
        COUNT(`Publication`.`id`) AS `count`
    FROM
        `Publications` AS `Publication`
    INNER JOIN(
            `HistoryStates` AS `PublicationStates->HistoryState`
        INNER JOIN `PublicationStates` AS `PublicationStates`
        ON
            `PublicationStates`.`id` = `PublicationStates->HistoryState`.`publicationState_id`
        )
    ON
        `Publication`.`id` = `PublicationStates->HistoryState`.`publication_id` AND `PublicationStates`.`stateName` = 'Vendida'
    WHERE
        (
            (
                `Publication`.`deletedAt` > '2018-01-20 14:07:58' OR `Publication`.`deletedAt` IS NULL
            ) AND(
                `Publication`.`carState` = 'Usado' AND `Publication`.`fuel` = 'Diesel' AND `Publication`.`year` = 1974
            )

    That it's ok
    But then this:

    SELECT
        `Publication`.*,
        `PublicationStates`.`id` AS `PublicationStates.id`,
        `PublicationStates`.`stateName` AS `PublicationStates.stateName`,
        `PublicationStates->HistoryState`.`publication_id` AS `PublicationStates.HistoryState.publication_id`,
        `PublicationStates->HistoryState`.`publicationState_id` AS `PublicationStates.HistoryState.publicationState_id`,
        `PublicationStates->HistoryState`.`createdAt` AS `PublicationStates.HistoryState.createdAt`,
        `PublicationStates->HistoryState`.`updatedAt` AS `PublicationStates.HistoryState.updatedAt`
    FROM
        (
        SELECT
            `Publication`.`id`,
            `Publication`.`brand`,
            `Publication`.`group`,
            `Publication`.`modelName`,
            `Publication`.`kms`,
            `Publication`.`price`,
            `Publication`.`year`,
            `Publication`.`fuel`,
            `Publication`.`observation`,
            `Publication`.`imageGroup_id`,
            `Publication`.`carState`,
            `Publication`.`codia`,
            `Publication`.`name`,
            `Publication`.`email`,
            `Publication`.`phone`,
            `Publication`.`createdAt`,
            `Publication`.`updatedAt`,
            `Publication`.`deletedAt`,
            `Publication`.`publicationDetail_id`,
            `Publication`.`user_id`
        FROM
            `Publications` AS `Publication`
        WHERE
            (
                (
                    `Publication`.`deletedAt` > '2018-01-20 14:07:58' OR `Publication`.`deletedAt` IS NULL
                ) AND(
                    `Publication`.`carState` = 'Usado' AND `Publication`.`fuel` = 'Diesel' AND `Publication`.`year` = 1974
                )
            ) AND(
            SELECT
                `HistoryState`.`publication_id`
            FROM
                `HistoryStates` AS `HistoryState`
            INNER JOIN `PublicationStates` AS `PublicationState`
            ON
                `HistoryState`.`publicationState_id` = `PublicationState`.`id`
            WHERE
                (
                    `Publication`.`id` = `HistoryState`.`publication_id`
                )
            LIMIT 1
        ) IS NOT NULL
    LIMIT 0,
    9
    ) AS `Publication`
    INNER JOIN(
            `HistoryStates` AS `PublicationStates->HistoryState`
        INNER JOIN `PublicationStates` AS `PublicationStates`
        ON
            `PublicationStates`.`id` = `PublicationStates->HistoryState`.`publicationState_id`
        )
    ON
        `Publication`.`id` = `PublicationStates->HistoryState`.`publication_id` AND `PublicationStates`.`stateName` = 'Vendida'

    I don't know what I am doing wrong

  26. miradnan commented on Jun 29, 2021

    @miradnan

    I am facing this issue. It works when I create a primary key field. But not without primary key.

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

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions