Mysql - LEFT JOIN与COUNT

fre*_*rks 2 mysql

我有2个数据库表

  1. 目录
  2. directory_category

它们分别通过两个表中的类别ID(作为cat_id和id)链接


我想列出directory_category中的所有类别,同时计算在此类别的目录中找到多少条记录(使用单个sql查询)

我试过了

SELECT 
      directory_category.id
      directory_category.category_name
      directory.cat_id
      count(directory) as total_records
      FROM directory_category
      LEFT JOIN directory
      ON directory_category.id = directory.cat_id
Run Code Online (Sandbox Code Playgroud)

此查询仅生成一条记录,而total_records似乎是整个目录表的总和

Har*_*pta 7

SELECT 
    directory_category.id,
    directory_category.category_name,
    directory.cat_id,
    COUNT(directory.id) AS total_records
FROM directory_category
LEFT JOIN directory ON directory_category.id = directory.cat_id
GROUP BY directory_category.id
Run Code Online (Sandbox Code Playgroud)