假设我们有这张桌子
t1
--------------------------------
category_id | name | lft | rgt
--------------------------------
1 cat1 1 8
2 cat2 2 3
3 cat3 4 7
4 cat4 5 6
t2
-------------------------------
item_id | category_id
--------------------------------
1 1
2 2
3 3
4 4
MySQL 中有没有办法获取一个类别拥有的项目数(包括那些属于其子项的项目)?像这样的东西...
-------------------------------
category_id | item_count
--------------------------------
1 4
2 1
3 2
4 1
我无法连接获取 category_ids 的查询和获取子类别计数的查询。
SELECT category_id FROM t1 WHERE <some conditions here>
SELECT
COUNT(*) AS item_count,
category_id
FROM
t2
WHERE
t2.category_id IN
(
SELECT
node.category_id
FROM
t1 AS node,
t1 AS parent
WHERE
node.lft BETWEEN parent.lft AND parent.rgt
AND parent.category_id = 5 <---- How do I pass the category ids of the first query
here?
)