限定 MONTHNAME 中的列


Qualify a column within MONTHNAME

我遇到了一个小问题,我似乎无法解决。

我正在我的数据库中搜索用户在一个月内获得的评论总数,然后在图表中绘制。

我遇到的问题是当我使用 MONTHNAME 在我的 SQL 语句中使用时,如果我使用

$this->db->select('MONTHNAME(`created_on`), COUNT(`comment.id`)');

如果我尝试使用列前面的表名限定它,我得到created_on字段是不明确的

public function getTotalCommentsPerMonth() {
    $this->db->select('MONTHNAME(`photo_comment.created_on`), COUNT(`comment.id`)');
    $this->db->from('photo_comment');        
    $this->db->join('photo', 'photo.id = photo_comment.photo_id');
    $this->db->where('photo.userId', $this->auth->userid());
    return $this->db->get()->result_array();
}

我得到Unknown column 'photo_comment.created_on' in 'field list'您在使用MONTHNAME时无法限定列吗?

感谢您的帮助

更新:photo_comment和照片表概述

## photo_comment
comment_id
photo_id
user_id
created_on
comment
## photo
id
title
file_name
upload_path
userId
description
created_on

如果您在查询中添加反引号,则需要为活动记录的select()函数设置FALSE,它将限制活动记录添加反引号,并且您正在使用COUNT(comment.id)并且查询中没有名为comment的表,我想您需要从photo_comment中计算id,我为表格使用了短别名,因此形式更具可读性

public function getTotalCommentsPerMonth() {
    $this->db->select('MONTHNAME(pc.`created_on`) AS `month_name`, 
                      COUNT(pc.`comment_id`)  AS `comment_count`',FALSE);
    $this->db->from('photo_comment pc');        
    $this->db->join('photo p', 'p.id = pc.photo_id');
    $this->db->where('p.userId', $this->auth->userid());
    return $this->db->get()->result_array();
}

注意:使用聚合函数而不对其进行分组将 结果为一行,如果您需要所有照片的评论计数 用户数量,您应该按用户分组pc.photo_id在活动记录中,您可以 这样做

public function getTotalCommentsPerMonth() {
    $this->db->select('MONTHNAME(pc.`created_on`) AS `month_name`, 
                      COUNT(pc.`comment_id`)  AS `comment_count`',FALSE);
    $this->db->from('photo_comment pc');        
    $this->db->join('photo p', 'p.id = pc.photo_id');
    $this->db->where('p.userId', $this->auth->userid());
    $this->db->group_by("pc.photo_id");
    return $this->db->get()->result_array();
}