【问题标题】:Qualify a column within MONTHNAME限定 MONTHNAME 中的列
【发布时间】:2014-04-08 04:42:06
【问题描述】:

我遇到了一个我似乎无法理解的小问题。

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

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

$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

【问题讨论】:

  • 能否提供一下photo_comment和photo table的概要结构。
  • 刚刚完成,希望对您有所帮助。
  • 看起来很奇怪,你做的都是正确的。顺便说一句,`comment.id 是什么?

标签: php mysql sql codeigniter


【解决方案1】:

如果您在查询中添加反引号,则需要为活动记录的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();
}

【讨论】:

  • 这似乎解决了问题。谢谢
猜你喜欢
  • 2018-03-10
  • 2019-05-26
  • 2014-09-19
  • 1970-01-01
  • 2017-01-15
  • 2019-04-23
  • 2017-06-05
  • 1970-01-01
相关资源
最近更新 更多