【问题标题】:Without changing sql mode=only_full_group_by mode how can I execute group by in cakephp?在不更改 sql mode=only_full_group_by 模式的情况下如何在 cakephp 中执行 group by?
【发布时间】:2021-09-02 09:35:46
【问题描述】:

我正在尝试从交易表中获取每月的金额总和。我在 cakephp 函数下面写了我想要的输出。

public function getLastSixMOnthsExpenses($since_date, $t_type)
{
           $query = $this->find()->select([
                 'month' => $this->find()->func()->monthname([
                   'created' => 'identifier'
                ]),
               'amount' => $this->find()->func()->sum('Transactions.amount')
            ])
            ->where([
               'Transactions.created >='=>  $since_date->modify('6 months ago')->startOfMonth(),
               'Transactions.created <='=>  $since_date->endOfMonth(),
               'Transactions.transaction_type '=>$t_type
            ])
            ->group(['month'])
            ->order(['Transactions.created'=>'ASC'])
           ;
    
           return $query;
 }

我遇到了错误

Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'kjoumaa_kamaljoumaa.Transactions.created' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

不改变sql模式,如何在这里运行group by?

【问题讨论】:

    标签: cakephp cakephp-3.x


    【解决方案1】:

    改为按聚合排序。

    由于您按月份分组,因此这些组中的所有 created 字段将属于同一月份,例如,一组中的所有 created 字段将指向比另一个组,因此您可以简单地从组中选择最小值或最大值:

    ->orderAsc(function (
        \Cake\Database\Expression\QueryExpression $exp,
        \Cake\ORM\Query $query
    ) {
        return $query->func()->min(
            $query->identifier('Transactions.created')
        );
    })
    
    ORDER BY MIN(Transactions.created) ASC
    

    此外,如果您将月份选择为数字而不是名称,则可以在该字段中进行排序。

    【讨论】:

    • 我应该在订购时更换它吗?按订单替换后出现错误错误:SQLSTATE [42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;查看与您的 MariaDB 服务器版本相对应的手册,了解在第 1 行的“ASC”附近使用的正确语法
    • @NiloyRony 检查正在生成的完整 SQL。
    猜你喜欢
    • 2012-09-08
    • 2012-01-26
    • 2018-03-23
    • 1970-01-01
    • 2012-10-27
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多