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;
}
什麼特殊字段'comment_count'爲'incident'表?您可以使用事件(評論添加/刪除)來增加它,而不是每次計數。 – biakaveron