MySQL - 如何从表中获取结果,以及在一个查询中有多少个连接项的计数?

时间:2012-05-19 02:05:47

标签: mysql sql

我有这样的查询:

select display_order , section_name , solution_section_id from solution_sections order by display_order

这是非常基础的,并获得特定讨论的部分。它有效。

我想要做的是同时显示每个部分的评论数量。所以我想在评论表上进行联接,并计算有多少评论。

以下是其他表的架构:

mysql> describe suggested_solution_comments;
+-----------------------+----------------+------+-----+---------+----------------+
| Field                 | Type           | Null | Key | Default | Extra          |
+-----------------------+----------------+------+-----+---------+----------------+
| comment_id            | int(10)        | NO   | PRI | NULL    | auto_increment |
| problem_id            | int(10)        | NO   |     | NULL    |                |
| suggested_solution_id | int(10)        | NO   |     | NULL    |                |
| commenter_id          | int(10)        | NO   |     | NULL    |                |
| comment               | varchar(10000) | YES  |     | NULL    |                |
| solution_part         | int(3)         | NO   |     | NULL    |                |
| date                  | date           | NO   |     | NULL    |                |
| guid                  | varchar(50)    | YES  | UNI | NULL    |                |
+-----------------------+----------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

mysql> describe solution_sections;
+---------------------+---------------+------+-----+---------+----------------+
| Field               | Type          | Null | Key | Default | Extra          |
+---------------------+---------------+------+-----+---------+----------------+
| solution_section_id | int(10)       | NO   | PRI | NULL    | auto_increment |
| display_order       | int(10)       | NO   |     | NULL    |                |
| section_name        | varchar(1000) | YES  |     | NULL    |                |
+---------------------+---------------+------+-----+---------+----------------+

所以它必须是一个关于solution_section_id和solution_part的连接(那些是外键,即使它们的名字有点不一致),其中problem_id = some id。

但是如何获得suggest_solution_comments表中返回注释数量的计数?

谢谢!

2 个答案:

答案 0 :(得分:1)

SELECT solution_sections.display_order, solution_sections.section_name, solution_sections.solution_section_id, COUNT(suggested_solution_comments.comment_id) FROM solution_sections, suggested_solution_comments GROUP BY solution_sections.solution_section_id

也许尝试这样的事情?自从我触及表连接以来,它已经有一段时间了,你的表命名对我来说看起来很混乱。

答案 1 :(得分:1)

使用外部联接更新:

select s.display_order, s.section_name, s.solution_section_id
      ,count(c.comment_id) AS comment_count
  from solution_sections s
  left outer join suggested_solution_comments c ON (c.solution_part = s.solution_section_id)
  group by s.display_order, s.section_name, s.solution_section_id
  order by display_order