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条)

报告相同问题?

悬赏问题

  • ¥20 阿里云python代码求解
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路