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の結合である必要があります(これらは、多少一貫性のない名前が付けられていますが、外部キーです)。ここで、problem_id =someidです。

しかし、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 に答える