Skip to content

LEFT JOIN instead of INNER JOIN in findAndCountAll, count part #3936

Closed

Description

@Orvisky

Is there any solution to do LEFT JOIN instead of INNER JOIN? I tryed to search but nothing found.

Example:

  • i use datatables, and request for example contact.name
  • i use findAndCountAll method
finder.include = [
        {model: db.User, attributes: ['id', 'nickname'], paranoid: false, required: true},
        {model: db.Contact, attributes: ['id', 'name', 'surname'], paranoid: false, where: {is_main_contact: true}}
    ];

(count part):
SELECT count(company.id) AS count FROM acrm_companies AS company INNER JOIN acrm_users AS user ON company.created_by = user.id INNER JOIN acrm_contacts AS contact ON company.company_id = contact.company_company_id AND contact.is_main_contact = true WHERE (company.deleted IS NULL AND (company.is_latest = true));

  • but, when company has no contact, than it will be not showed in result beacuse of INNER JOIN
  • but, i can't remove required: true / where: {..}, because when you search in datatables, query want to search in contact.name (it come as attribute from datatable) but it fail (because required: false don't include contact model)

So, solution can be LEFT JOIN, which include all companies and they have not to have contacts, something like this:

SELECT count(company.id) AS count FROM acrm_companies AS company INNER JOIN acrm_users AS user ON company.created_by = user.id LEFT JOIN acrm_contacts AS contact ON company.company_id = contact.company_company_id AND contact.is_main_contact = true WHERE (company.deleted IS NULL AND (company.is_latest = true));

Activity

  1. mickhansen commented on Jun 15, 2015

    @mickhansen
    Contributor

    required: true forces an inner join, use required: false to force a left join.

  2. Orvisky commented on Jun 15, 2015

    @Orvisky
    Author

    It is bugged - query is not builded same in count part as in data part,

    i used required: false. It do LEFT OUTER JOIN in second (data query), but not that first (count) query. It completly ignores include it in count when required: false. Take a look:

    ...
    finder.include = [
            {model: db.User, attributes: ['id', 'nickname'], paranoid: false, required: true},
            {model: db.Contact, attributes: ['id', 'name', 'surname'], paranoid: false, where: {is_main_contact: true}, required: false}
        ];
    ...
    db.Company.findAndCountAll(finder)
    

    1.query of method findAndCountAll()
    SELECT count(company.id) AS count FROM acrm_companies AS company INNER JOIN acrm_users AS user ON company.created_by = user.id WHERE (company.deleted IS NULL AND (company.is_latest = true));

    2.query of method findAndCountAll() (right after first)
    SELECT company.id, company.company_id, company.name, company.name_alt, company.ico, contact.surname, company.ico, user.nickname, company.created, user.id AS user.id, user.nickname AS user.nickname, contact.id AS contact.id, contact.name AS contact.name, contact.surname AS contact.surname FROM acrm_companies AS company INNER JOIN acrm_users AS user ON company.created_by = user.id LEFT OUTER JOIN acrm_contacts AS contact ON company.company_id = contact.company_company_id AND contact.is_main_contact = true WHERE (company.deleted IS NULL AND (company.is_latest = true)) ORDER BY company.id ASC LIMIT 0, 50;

  3. changed the title [-]LEFT JOIN instead of INNER JOIN[/-] [+]LEFT JOIN instead of INNER JOIN in findAndCountAll, count part[/+] on Jun 15, 2015
  4. Orvisky commented on Jun 25, 2015

    @Orvisky
    Author

    Anything new please about this problem?

  5. mickhansen commented on Jun 25, 2015

    @mickhansen
    Contributor

    Haven't had time to look at it.
    You can speed things along by providing a fully reproduceable example, even better a failing unit/integration test.

  6. added
    type: bug
    on Jun 25, 2015
  7. mickhansen commented on Jun 25, 2015

    @mickhansen
    Contributor

    The bug appears to be that the JOIN probably shouldn't even be in the COUNT part since you can't use the where part to filter the main query if it's not an inner join.

  8. mickhansen commented on Jun 25, 2015

    @mickhansen
    Contributor
  9. Orvisky commented on Jun 25, 2015

    @Orvisky
    Author

    Thx for fast reply :) If i make something, i will give a notice.

  10. Orvisky commented on Jun 25, 2015

    @Orvisky
    Author

    Try look at line https://github.com/sequelize/sequelize/blob/master/lib/model.js#L1397 , what do you think about changing to this:

    return include.required || include.hasIncludeRequired || include.where;

    • it works but i dont have test right now, mabye it can bug somewhere
  11. janmeier commented on Jun 25, 2015

    @janmeier
    Member

    Why should the include be kept if it is not required? The query will return both rows which have any contacts attached, and those which doesn't. The number of companies should still be the same, without and without the include part right. The only case is when required is true, and the join is limiting the number of company rows

  12. Orvisky commented on Jun 25, 2015

    @Orvisky
    Author

    But, imagine, that you have table on page and you search in table via API (ex. datatables) and you search in datatables via search input. On the API side, you have findAndCountAll. When you do search, than, you have to include model also in 'count' query, otherwise it will give you error of unknow attribute. Off course LEFT JOIN can be empty, but you have to join that table. And, off course, you dont want INNER JOIN if you expect that joining table can be empty (for ex.)

  13. mickhansen commented on Jun 25, 2015

    @mickhansen
    Contributor

    @Orvacko If you need the join table in the count it has to be a inner join, else it doesn't really make sense.

  14. Orvisky commented on Jun 25, 2015

    @Orvisky
    Author

    Simple example (actual models simplified) that throws you an error:

    var User = sequelize.define('user', {
            nickname: { type: DataTypes.STRING(64), allowNull:true, validate: { isAlphanumericExt: true }}
        }, {
        });
    
    var Call = sequelize.define('call', {
            user_id: { type: DataTypes.INTEGER, validate: {  }},
        }, {
            classMethods: {
                associate: function (models) {
                    Call.belongsTo(models.User, { foreignKey: 'user_id' });
                }
            }
        });
    
    var finder = {
            attributes: ['id', 'user.nickname'],
            where: {id: 739164, 'user.nickname': {$like: '%david%'}},
            include: [
                {model: db.User, attributes: ['nickname'], paranoid: false, required: false}
            ],
            raw: true
        };
    
        db.Call.findAndCountAll(finder).then(function(result) {
            console.log(result);
        });
    • sql
    SELECT count(*) AS `count`
    FROM `acrm_calls` AS `call`
    WHERE (`call`.`deleted` IS NULL
           AND (`call`.`id` = 739164
                AND `user`.`nickname` LIKE '%david%'));
    • error:
    Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'user.nickname' in 'field list'
    
    • so in this case, you have to do RIGHT JOIN in count (You can do INNER JOIN off course when you know that record must have user). But when joining model is not required, i have to do RIGHT JOIN
    • after fix i mentioned above
    var finder = {
            attributes: ['id', 'user.nickname'],
            where: {id: 739164, 'user.nickname': {$like: '%david%'}},
            include: [
                {model: db.User, attributes: ['nickname'], paranoid: false, required: false, where: {}}
            ],
            raw: true
        };
    • output SQL with no errors:
    SELECT count(`call`.`id`) AS `count`
    FROM `acrm_calls` AS `call`
    LEFT OUTER JOIN `acrm_users` AS `user` ON `call`.`user_id` = `user`.`id`
    WHERE (`call`.`deleted` IS NULL
           AND (`call`.`id` = 739164
                AND `user`.`nickname` LIKE '%david%'));
  15. mickhansen commented on Jun 25, 2015

    @mickhansen
    Contributor
    attributes: ['id', 'user.nickname'],
    where: {id: 739164, 'user.nickname': {$like: '%david%'}},
    

    We don't officially support that syntax, so that's why you're seeing an error. We don't support adding a nested key to a toplevel attributes or where at the moment.

    You can look at #3095 for a feature request for querying a include outside of include.where

    I do see the problem here, even if we did officially support it, Sequelize doesn't know that you need the join inside the count.

  16. Orvisky commented on Jun 25, 2015

    @Orvisky
    Author

    Hm, and, what about that fix / feature i mentioned (or some other, better parameter) ? When i explicit say that include User model and it can do RIGHT JOIN, everything is Ok. I was expecting behavior like that is mention here: http://docs.sequelizejs.com/en/latest/docs/models-usage/#nested-eager-loading. WIth my fix, it is same behavior as in .doc , or not?

    This will produce an outer join. However, a where clause on a related model will create an inner join and return only the instances that have matching sub-models. To return all parent instances, you should add required: false.

  17. mickhansen commented on Jun 25, 2015

    @mickhansen
    Contributor

    The behaviour described in the docs are for find* methods generally.
    count has special logic so as not too muck up the query too much.

  18. renatoargh commented on Oct 4, 2015

    @renatoargh

    Is there a way to force left joins in older versions like "sequelize": "^1.7.10"? Thanks in advance

  19. janmeier commented on Oct 4, 2015

    @janmeier
    Member

    @renatoargh Unfortunately not

  20. satornure commented on Nov 24, 2015

    @satornure

    I have the same problem, i tried

    SiteMenu.count({
          attributes: ['id', 'placeholders.id'],
          include: [
            {model: MenuPlaceholder, as: 'placeholders', required: false}
          ],
          where: {
            siteId: this.site.id,
            'placeholders.id': null
          }
        });
    

    The result was

    SELECT `SiteMenu`.`id`, `placeholders`.`id`, count(`SiteMenu`.`id`) AS `count` FROM `site_menues` AS `SiteMenu` LEFT OUTER JOIN `menu_placeholders` AS `placeholders` ON `SiteMenu`.`id` = `placeholders`.`menuId` WHERE `SiteMenu`.`siteId` = 1 AND `SiteMenu`.`placeholders.id` IS NULL;
    

    But i need placeholders.id` IS NULL` instead of SiteMenu.placeholders.id IS NULL
    Pls help

  21. janmeier commented on Nov 24, 2015

    @janmeier
    Member

    Try '$placeholders.id$': null

  22. satornure commented on Nov 24, 2015

    @satornure

    it works nice, thanks

  23. janmeier commented on Nov 24, 2015

    @janmeier
    Member

    Try upgrading to a more recent version

  24. rcolmenarez commented on Mar 2, 2016

    @rcolmenarez

    Any advance in this bug?

  25. nikuph commented on Mar 18, 2016

    @nikuph

    Try '$placeholders.id$': null

    This also helped me out for an OUTER JOIN with WHERE.
    Is this somewhere in the documentation?

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