我遇到了一个小问题,我似乎无法理解。
我在我的数据库中搜索用户一个月内收到的评论总数,然后在图表中绘图。
我遇到的问题是当我使用
时在我的SQL语句中使用MONTHNAME
$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
答案 0 :(得分:0)
如果要在查询中添加反引号,则需要为活动记录的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();
}
注意:使用Aggregate Fucntions而不对其进行分组将会 如果您需要所有照片的评论计数,则会生成一行 用户应该按照他们的分组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();
}