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
          ),
      );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题