Mysql - LEFT JOIN与COUNT

时间:2013-05-16 08:02:33

标签: mysql

我有2个数据库表

  1. 目录
  2. directory_category
  3. 它们分别通过两个表中的类别ID(作为cat_id和id)链接


    我想列出 directory_category 中的所有类别,同时计算此类别目录中找到的记录数(使用单个SQL查询)< / p>

    我试过了

    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
    

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

猜测(和快速),我会说:

SELECT 
    directory_category.id,
    directory_category.category_name,
    directory.cat_id,
    count
FROM
    directory_category
LEFT JOIN
    (
        SELECT
            count(directory) as total_records
        FROM
            directory
        INNER JOIN
            directory_category
        ON
            directory_category.id = directory.cat_id
    ) AS count

但显然你需要玩它。