计算外键数量

时间:2012-09-11 13:51:56

标签: mysql


我有三张桌子。

1。fi_category

+----+-----------------+-----------------+
| id | name            | slug            |
+----+-----------------+-----------------+

2。fi_subcategory

+----+-----------------+-----------------+-------------+
| id | name            | slug            | category_id |
+----+-----------------+-----------------+-------------+

第3。fi_business_subcategory

+----+-------------+----------------+
| id | business_id | subcategory_id |
+----+-------------+----------------+

我基本上要做的是,

  1. 获取所有类别
  2. 获取属于类别的所有子类别。
  3. 计算特定子类别的业务数量。
  4. 这是我尝试过的。

    SELECT 
        f.id,
        f.name,
        f.slug,
        f2.id,
        f2.name,
        f2.slug,
        COUNT(f3.business_id) as count
    FROM
        fi_category f
    LEFT JOIN 
        fi_subcategory f2 ON f.id = f2.category_id
    LEFT JOIN 
        fi_business_subcategory f3 ON f2.id = f3.subcategory_id
    

    但是上面的查询只提取了1条记录。我如何获取我想要的东西?

1 个答案:

答案 0 :(得分:2)

我会添加一个GROUP BY子句:

SELECT 
    f.id,
    f.name,
    f.slug,
    f2.id,
    f2.name,
    f2.slug,
    COUNT(f3.business_id) as count
FROM fi_category f
LEFT JOIN fi_subcategory f2 
    ON f.id = f2.category_id
LEFT JOIN fi_business_subcategory f3 
    ON f2.id = f3.subcategory_id
GROUP BY f.id,
    f.name,
    f.slug,
    f2.id,
    f2.name,
    f2.slug

或者在子查询中获取count()

SELECT f.id,
    f.name,
    f.slug,
    f2.id,
    f2.name,
    f2.slug,
    f3.cnt
FROM fi_category f
LEFT JOIN fi_subcategory f2 
    ON f.id = f2.category_id
LEFT JOIN
(
    select count(business_id) cnt, subcategory_id 
    from fi_business_subcategory
    group by subcategory_id
) f3 
    ON f2.id = f3.subcategory_id