SQL 查询 table 中包含类别和子类别的选择
SQL query for a selection from a table with categories and subcategories
类别结构table:
- id
- 标题
- parent_id
项目的结构table:
- id
- 标题
- is_active (0 和 1)
- category_id
table structure
表通过 one-to-many 关系与 category_id 字段相关联。那些。 1 个类别可以有很多项目。
类别 table 中的 two-level 层次结构。这定义了主要类别和子类别。类别是那些 parent_id = NULL 的记录。和子类别,这些是 parent_id = 某些 id.
的记录
一个项目可以同时属于主类别(其中 parent_id = null)和子类别 (child)。项目可以是活动的和不活动的(0 或 1)。
您需要查询 select 来自类别 table 的所有主要类别(其中 parent_id = null)具有活动项目 (is_active = 1) 并且有子类别也有活动项目。
即如果 child 子类别有 is_active = 0 的项目,则不显示此类别。
我只能选择主要类别,其中只有活动项目:
SELECT categories.title, count(analyses.id) FROM items
INNER JOIN categories on items.category_id = categories.id
WHERE categories.parent_id IS NULL
AND categories.is_active = 1
GROUP BY analyses.category_id
ORDER BY analyses_categories.title
但是有了子类就不行了,请哪位有经验的告诉我一下
有点不清楚您要 count
的内容(只是与 parent 关联的活动项目?),但我会使用 exists
找出哪些 exists
=15=] 还有活动项目:
select c.title, count(*)
from categories c
join item i on i.category_id = c.id
where c.parent_id is null and i.is_active = 1 and exists (
select 1
from categories c2
join item i on c2.id = i.category_id
where c2.parent_id = c.id and i.is_active = 1
)
group by c.title
类别结构table:
- id
- 标题
- parent_id
项目的结构table:
- id
- 标题
- is_active (0 和 1)
- category_id
table structure
表通过 one-to-many 关系与 category_id 字段相关联。那些。 1 个类别可以有很多项目。
类别 table 中的 two-level 层次结构。这定义了主要类别和子类别。类别是那些 parent_id = NULL 的记录。和子类别,这些是 parent_id = 某些 id.
的记录一个项目可以同时属于主类别(其中 parent_id = null)和子类别 (child)。项目可以是活动的和不活动的(0 或 1)。
您需要查询 select 来自类别 table 的所有主要类别(其中 parent_id = null)具有活动项目 (is_active = 1) 并且有子类别也有活动项目。 即如果 child 子类别有 is_active = 0 的项目,则不显示此类别。
我只能选择主要类别,其中只有活动项目:
SELECT categories.title, count(analyses.id) FROM items
INNER JOIN categories on items.category_id = categories.id
WHERE categories.parent_id IS NULL
AND categories.is_active = 1
GROUP BY analyses.category_id
ORDER BY analyses_categories.title
但是有了子类就不行了,请哪位有经验的告诉我一下
有点不清楚您要 count
的内容(只是与 parent 关联的活动项目?),但我会使用 exists
找出哪些 exists
=15=] 还有活动项目:
select c.title, count(*)
from categories c
join item i on i.category_id = c.id
where c.parent_id is null and i.is_active = 1 and exists (
select 1
from categories c2
join item i on c2.id = i.category_id
where c2.parent_id = c.id and i.is_active = 1
)
group by c.title