2012-12-13 21 views
1

COUNT表达我有2个表:编写SQL在Kohana中

事件(ID,incident_description) 评论(ID,incident_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]: * 修剪()预计参数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; 
       } 
+0

什么特殊字段'comment_count'为'incident'表?您可以使用事件(评论添加/删除)来增加它,而不是每次计数。 – biakaveron

回答

4

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

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

+0

这可以使用一点解释来说明错误行的哪一部分被解释为一个数组。 –

-1

对于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查询

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');