且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单个SQL查询中的多个计数

更新时间:2022-11-27 20:47:10

@ VoteyDisciple的回答是但他的查询需要一些改进:

@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:


  • IF()表达式是多余的,因为等式已返回1或0。

  • 取出连接条件中的 ts1.section_id = 1 ,或者永远不会获得其他 section_id 值。

  • 仅由 c.id 分组。我假设OP只需要每个类别一行,以及各个类别的每个 section_id 值的计数列。如果查询按 c.id,ts1.section_id 分组,则每个类别最多有四行。

  • 移动在选择列表中的逗号。漂浮在线条开始处的逗号看起来很丑陋。 ; - )

  • 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. ;-)