douxuexiao1748 2016-10-10 10:17
浏览 48
已采纳

在1个查询中选择类别,子类别和主题数

I have the following query:

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

What I want to accomplish is the following:

I want to select ALL parent categories (even if they don't have subcategories), and I want to count all the topics in every subcategory (a topic can only be posted in a subcategory, not in a category).

This query works half: it only selects the categories with subcategories, and only the subcategories which have topics in it.

Can someone fix this problem? Or give me a useful tip to solve this?

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • dropbox1111 2016-10-10 10:22
    关注

    Miss group by logic with the frm_topics table, and better put the filter in on clause instead of where clause during outer join.

    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  
    

    sql fiddle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动