我有三张桌子。
1。fi_category
+----+-----------------+-----------------+
| id | name | slug |
+----+-----------------+-----------------+
2。fi_subcategory
+----+-----------------+-----------------+-------------+
| id | name | slug | category_id |
+----+-----------------+-----------------+-------------+
第3。fi_business_subcategory
+----+-------------+----------------+
| id | business_id | subcategory_id |
+----+-------------+----------------+
我基本上要做的是,
这是我尝试过的。
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条记录。我如何获取我想要的东西?
答案 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