0

我有一个这样的查询:

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 的连接(即使它们的命名有些不一致,它们也是外键)其中问题 ID = 一些 ID。

但是,我将如何获得Suggested_solution_comments 表中返回评论的数量?

谢谢!

4

2 回答 2

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

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

于 2012-05-19T02:13:44.097 回答
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
于 2012-05-19T02:20:20.890 回答