【问题标题】:COUNT function in sql counting whole data in databasesql中的COUNT函数计算数据库中的整个数据
【发布时间】:2019-06-21 09:46:00
【问题描述】:

我正在尝试根据类别id计算数据库中的数据数量,我编写了以下代码行:

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);
}

但是,getPodcastByCategoryId($catId) 函数给出的 episodes = 3,这是表播客中存在的数据计数。

数据库中的数据

我的预期情节是类别 id 2 中的 2 集和类别 id 1 中的 1 集。

【问题讨论】:

  • 为什么不用INNER JOINs 到users & categories 而不是子查询?

标签: php arrays select count


【解决方案1】:

对于剧集,您应该使用 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
      ),
  );

【讨论】:

  • 它将返回所有类别 ID 的计数 2。
  • Distinct 我猜现在不需要了。
  • @SougataBose 。正确的应该是计数(*)不是不同的类别
猜你喜欢
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
  • 2010-10-15
  • 1970-01-01
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多