Multiple counts within a single SQL query

前端 未结 2 637
日久生厌
日久生厌 2020-12-28 09:10

I\'m trying to get the count of documents within 4 specific sections using the following code:

SELECT
    category.id
    , category.title
    , count(ts1.se         


        
2条回答
  •  梦谈多话
    2020-12-28 09:38

    @VoteyDisciple's answer is on the right track, but his query needs some improvements:

    SELECT c.id, c.title,
        SUM(ts1.section_id = 1) AS doc1,
        SUM(ts1.section_id = 2) AS doc2,
        SUM(ts1.section_id = 3) AS doc3,
        SUM(ts1.section_id = 4) AS doc4
    FROM category AS c
      LEFT JOIN category_link_section AS ts1
        ON (c.id = ts1.category_id)
    GROUP BY c.id;
    

    Explanations:

    • The IF() expressions are redundant because equality already returns 1 or 0.
    • Take the ts1.section_id=1 out of the join condition, or you'll never get the other section_id values.
    • Group by c.id only. I assume the OP only wants one row per category, and columns for counts of each section_id value for the respective category. If the query grouped by c.id, ts1.section_id, then there'd be up to four rows per category.
    • Move the commas in the select-list. Commas floating at the start of the line look ugly. ;-)

提交回复
热议问题