【问题标题】:Writing SQL with COUNT expression in Kohana在 Kohana 中使用 COUNT 表达式编写 SQL
【发布时间】:2012-12-13 08:37:15
【问题描述】:

我有 2 张桌子:

事件(id,incident_description) 评论(id、event_id、comment_description)

我想写这样的SQL表达式:

SELECT incident.*, COUNT(comment.id) AS com 
FROM incident 
LEFT JOIN comment ON comment.incident_id=incident.id 
GROUP BY incident.id 
ORDER BY com DESC

它在 phpmyadmin 中运行良好。

我用 ORM 写:

ORM::factory('incident')
->select('incident.*',array('COUNT("comment.id")', 'com'))
->join('comment', 'LEFT')
->on('comment.incident_id', '=', 'incident.id')
->group_by('incident.id')
->order_by('com', 'DESC')
->find_all();

但我得到一个错误: 系统/库/Database.php [296]: *trim() 期望参数 1 是字符串,给定数组*

来自 Database.php 的代码:

 foreach ($sql as $val)
                {
                        if (($val = trim($val)) === '') continue;

                        if (strpos($val, '(') === FALSE AND $val !== '*')
                        {
                                if (preg_match('/^DISTINCT\s++(.+)$/i', $val, $matches))
                                {
                                        $val            = $this->config['table_prefix'].$matches[1];
                                        $this->distinct = TRUE;
                                }
                                else
                                {
                                        $val = (strpos($val, '.') !== FALSE) ? $this->config['table_prefix'].$val : $val;
                                }

                                $val = $this->driver->escape_column($val);
                        }

                        $this->select[] = $val;
                }

【问题讨论】:

  • 对于incident 表的特殊列comment_count 怎么样?您可以使用事件(添加/删除评论)来增加它,而不是每次都计数。

标签: php kohana kohana-3


【解决方案1】:

array(DB::expr('COUNT("comment.id")'), 'com')

您不希望查询构建器尝试转义复杂的表达式或其他数据库函数。在这些情况下,您需要使用使用DB::expr 创建的数据库表达式。

【讨论】:

  • 这可以使用一点解释来澄清错误行的哪一部分被解释为数组。
【解决方案2】:

对于 Kohana 2,你想要这样的东西

ORM::factory('incident')
->select('incident.*','COUNT("comment.id") AS comments')
->join('comment', 'comment.incident_id', 'incident.id', 'LEFT')
->groupby('incident.id')
->orderby('comments', 'DESC')
->find_all();

或者使用数据库查询

DB::instance()->query('SELECT incident.*, COUNT(comment.id) AS comments 
FROM incident 
LEFT JOIN comment ON comment.incident_id = incident.id 
GROUP BY incident.id 
ORDER BY comments DESC');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2023-03-29
    • 2019-08-04
    相关资源
    最近更新 更多