簡體   English   中英

在1個查詢中選擇類別,子類別和主題數

[英]Select categories, subcategories and number of topics in 1 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

我要完成的工作如下:

我想選擇所有父類別(即使它們沒有子類別),並且我想計算每個子類別中的所有主題(主題只能發布在子類別中,而不能發布在類別中)。

該查詢工作一半:僅選擇帶有子類別的類別,並且僅選擇其中包含主題的子類別。

有人可以解決這個問題嗎? 還是給我一個有用的提示來解決這個問題?

提前致謝!

使用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  

sql小提琴

我現在有以下查詢:

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,標題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM