排序:将数据与关联的数据过滤器分组

时间:2019-02-20 13:19:29

标签: sequelize.js

我有一个分组的数据查询,该查询需要通过不包含在结果中的关联进行过滤。

尝试执行此操作时出现错误,因为生成的sql不是我期望的

    User.findAndCountAll({
        group: [
            sequelize.fn(
                'date_format',
                sequelize.col('User.createdAt'),
                '%Y-%m-%d'
            ),
        ],
        attributes: [
            [
                sequelize.fn(
                    'date_format',
                    sequelize.col('User.createdAt'),
                    '%Y-%m-%d'
                ),
                'date',
            ],
            [sequelize.fn('count', 'User.id'), 'count'],
        ],
        order: [sequelize.literal('date DESC')],
        include: [
            {
                model: models.UserSite,
                as: 'sites',
                required: true,
                where: {
                    tenantId: 'project1'
                },
                attributes: [],
            },
        ],
    });

结果查询为

   code: 'ER_WRONG_FIELD_WITH_GROUP',
     errno: 1055,
     sqlState: '42000',
     sqlMessage: 'Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column \'project.User.id\' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by',
     sql: 'SELECT `User`.* FROM (SELECT `User`.`id`, date_format(`User`.`createdAt`, \'%Y-%m-%d\') AS `date`, count(\'User.id\') AS `count` FROM `Users` AS `User` WHERE (`User`.`deletedAt` > \'2019-02-20 10:17:29\' OR `User`.`deletedAt` IS NULL) AND ( SELECT `userId` FROM `UserSites` AS `sites` WHERE (`sites`.`tenantId` = \'project1\' AND `sites`.`userId` = `User`.`id`) LIMIT 1 ) IS NOT NULL GROUP BY date_format(`User`.`createdAt`, \'%Y-%m-%d\') ORDER BY date DESC LIMIT 0, 25) AS `User` INNER JOIN `UserSites` AS `sites` ON `User`.`id` = `sites`.`userId` AND `sites`.`tenantId` = \'project1\' ORDER BY date DESC;' },
  original: 
   {   Error: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'project.User.id' which is not functionally dependent on columns in GROUP B  Y clause; this is incompatible with sql_mode=only_full_group_by

include不存在时,查询工作正常。

1 个答案:

答案 0 :(得分:0)

您好,在Db中运行以下查询-

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

这是一个临时修复程序,如果您的数据库服务器重新启动,它将被撤消。每当我们的Db服务器重新启动时,您将需要添加脚本来运行此查询。

有关更多详细信息,建议您阅读-https://dev.mysql.com/doc/refman/8.0/en/group-by-handling.html

您还要创建一个名为-date的新属性,无需在组选项中创建参数gain。您可以直接在组选项中使用参数。