![](/img/trans.png)
[英]How to write a MySQL query that will limit the results of a joined table or tables and also count the number of items in the joined table or tables?
[英]MySQL - how to get results back from a table, and the count of how many joined items there are in one query?
我有這樣的查詢:
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。
但是,如何獲取suggested_solution_comments表中返回的注釋數量?
謝謝!
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
也許嘗試這樣的事情? 自從我觸及表連接以來,它已經有一段時間了,你的表命名看起來讓我很困惑。
外連接更新:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.