用多个字段进行分组,结果成为错误

时间:2018-08-28 05:23:58

标签: node.js sequelize.js

我的查询如下所示:

 db.test.findAll({
            group: ['source'],
            attributes: ['source','source_id', [Sequelize.fn('COUNT', 'source'), 'count']],
            order: [[Sequelize.literal('count'), 'DESC']],
            raw: true
        }).then((sources) => {
            console.log('source is ' + sources);
        }).catch((err) => {
            console.log('error i is ' + err);
        })

test.js

module.exports = function (sequelize, DataTypes) {
    const test = sequelize.define('test', {
        id: {primaryKey: true, type: DataTypes.INTEGER, autoIncrement: true, allowNull: false, unique: true},
        source: {type: DataTypes.STRING, allowNull: false},
        source_id: {type: DataTypes.STRING, allowNull: false},

    });

    return test
};

运行该查询后,它立即提示我这个错误:

Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'db.test.source_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

1 个答案:

答案 0 :(得分:2)

也尝试在group by子句中使用source_id。因为在这里SQL get混淆了从多个中选择哪个source_id。您有groupBy来源,因此可以选择,但souce_id仍然不明确

 db.test.findAll({
                group: ['source', 'source_id'],
                attributes: ['source','source_id', [Sequelize.fn('COUNT', 'source'), 'count']],
                order: [[Sequelize.literal('count'), 'DESC']],
                raw: true
            }).then((sources) => {
                console.log('source is ' + sources);
            }).catch((err) => {
                console.log('error i is ' + err);
            })