我有以下查询:
SELECT
c.frm_category_id,
c.name,
c.slug,
s.frm_category_id,
s.name,
s.slug,
IFNULL(COUNT(t.frm_topic_id),0)
FROM
frm_categories AS c
LEFT JOIN
frm_categories AS s
ON
c.frm_category_id = s.parent_frm_category_id
LEFT JOIN
frm_topics AS t
ON
s.frm_category_id = t.frm_category_id
WHERE
c.active = 1
AND
s.active = 1
ORDER BY
c.frm_category_id ASC,
s.frm_category_id ASC
我想要完成的是:
我想选择所有父类别(即使他们没有子类别),我想计算每个子类别中的所有主题(主题只能在子类别中发布,而不是在类别中)
此查询工作一半:它只选择具有子类别的类别,并且仅选择包含主题的子类别。
有人能解决这个问题吗?或者给我一个有用的提示来解决这个问题?
提前致谢!
答案 0 :(得分:1)
使用frm_topics表按逻辑分组,最好在外连接期间将过滤器放在on子句而不是where子句中。
SELECT
c.frm_category_id,
c.name,
c.slug,
s.frm_category_id sub_cate_id,
s.name,
s.slug,
IFNULL(tpc_count,0)
FROM
frm_categories AS c
LEFT join
frm_categories AS s
on
c.frm_category_id = s.parent_frm_category_id and c.active = 1 and s.active = 1
LEFT JOIN
(select frm_category_id, count(1) tpc_count from
frm_topics group by frm_category_id)AS t
ON
s.frm_category_id = t.frm_category_id
答案 1 :(得分:0)
我现在有以下查询:
SELECT
c.frm_category_id,
c.name,
c.slug,
s.frm_category_id,
s.name,
s.slug
FROM
frm_categories AS c
LEFT JOIN(
SELECT
frm_category_id,
parent_frm_category_id,
name,
slug
FROM
frm_categories
WHERE
parent_frm_category_id != 0
) AS s
ON
c.frm_category_id = s.parent_frm_category_id
WHERE
c.parent_frm_category_id = 0
ORDER BY
c.frm_category_id ASC
它适用于一部分:我现在获得所有类别,包含子类别的类别和没有类别的类别。
我现在要添加的唯一内容是计算每个SUBCATEGORY中的所有主题
表:主题
frm_topic_ic,frm_category_id,title