微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 使用聚合(分组)函数进行CGridView过滤 – 例如MAX()

我有一个CGridView,它使用MAX()mysql列为其中一列提供数据.我有使用排序,但我无法弄清楚过滤.我假设我可以使用CDbCriteria :: compare()调用来设置它,但它不起作用.想法?

我的搜索功能

    $criteria = new CDbCriteria;
    $criteria->condition = 't.is_deleted = 0 and is_admin = 0';
    // get last note date
    $criteria->select = array('t.*', 'MAX(n.visit_date) AS last_note');
    $criteria->join = 'LEFT JOIN notes n ON t.id = n.distributor_id';
    $criteria->group = 't.id';
    $criteria->order = 't.status';

    $criteria->compare('t.type', $this->type);
    $criteria->compare('t.name', $this->name, true);
    $criteria->compare('t.city', $this->city, true);
    $criteria->compare('t.state', $this->state);
    $criteria->compare('last_note', $this->last_note);



    return new CActiveDataProvider('distributor', array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => 20
            ),
            'sort' => array(
                'defaultOrder' => 'name',
                'attributes' => array(
                    'last_note' => array(
                        'asc' => 'last_note',
                        'desc' => 'last_note DESC'
                    ),
                )
            ),
        ));

在我看来,我只是设置了名称和值.

我得到的错误是CDbCommand无法执行sql语句:sqlSTATE [42S22]:找不到列:1054’where子句’中的未知列’last_note’

编辑:我发现这样做的唯一方法是(因为你不能在where子句中有聚合函数)检查$_GET数组的last_note值,并添加一个having子句.注意,这不是参数化或任何其他东西,我只是想粗略地看看它是否会起作用:

if(isset($_GET['distributor']['last_note']) && $_GET['distributor']['last_note'] != '') {
        $criteria->having = 'MAX(n.visit_date)=\'' . $this->last_note . "'";
}

我讨厌像这样使用模型中的请求变量,但是我没有其他的东西可以做.

解决方法:

你走在正确的轨道上.使用having过滤MAX()和SUM()等聚合函数.在这样的查询中,您可能应该添加一个组,否则当分发者在同一天有多个笔记时(假设t.id是主键),您的结果中会有大量重复数据.其次,您应该使用命名参数而不是将变量直接放入sql中.所以,而不是比较(‘last_note’…你最终得到这样的东西:

$criteria->group = 't.id';
$criteria->having = 'MAX(n.visit_date) = :last_note';
$criteria->params = array(':last_note' => $this->last_note);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐