douyan7916 2019-01-28 11:37
浏览 121
已采纳

SQL中的COUNT函数计算数据库中的整个数据

I am trying to count the number of data in the database according to the category id and I have written the following lines of code:

public function getPodcastByCategoryId($catId){
    $args = array(
        'fields' => array(
                    'podcast.id', 
                    'podcast.title',  
                    'podcast.description', 
                    'podcast.duration',
                    'podcast.audio',
                    'podcast.image',
                    'podcast.category',
                    'podcast.added_date',
                    'categories.title AS category_title',
                    '(SELECT users.full_name FROM users WHERE id = podcast.added_by) as author',
                    '(SELECT COUNT(category) FROM podcast WHERE category = podcast.category) as episodes'
                ),
        'join'   => "LEFT JOIN categories on podcast.category = categories.id",
        'where' => array(
            'category' => $catId
        ),
    );
    return $this->select($args);
}

However, the function getPodcastByCategoryId($catId) is giving episodes = 3 which is the count of data present in table podcast.

Data in database:

data in database

My expected episodes would be 2 in category id 2 and 1 in category id 1.

  • 写回答

1条回答 默认 最新

  • douza9835 2019-01-28 11:43
    关注

    for episode you should use COUNT(*)

    $args = array(
          'fields' => array(
                      'podcast.id', 
                      'podcast.title',  
                      'podcast.description', 
                      'podcast.duration',
                      'podcast.audio',
                      'podcast.image',
                      'podcast.category',
                      'podcast.added_date',
                      'categories.title AS category_title',
                      '(SELECT users.full_name FROM users WHERE id = podcast.added_by) as author',
                      '(SELECT COUNT(*) FROM podcast WHERE categories.category = podcast.category) as episodes'
                  ),
          'join'   => "LEFT JOIN categories on podcast.category = categories.id",
          'where' => array(
              'category' => $catId
          ),
      );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!