MySQL查询用于从两个表中选择和计算某些字段

时间:2014-01-04 10:56:04

标签: mysql

有MySQL表post

mysql> desc post;
+---------------+----------------+------+-----+---------+----------------+
| Field         | Type           | Null | Key | Default | Extra          |
+---------------+----------------+------+-----+---------+----------------+
| post_id       | int(11)        | NO   | PRI | NULL    | auto_increment |
| post_content  | varchar(50000) | NO   |     | NULL    |                |
| post_date     | datetime       | NO   |     | NULL    |                |
| post_summary  | varchar(1000)  | YES  |     | NULL    |                |
| post_title    | varchar(300)   | NO   |     | NULL    |                |
| post_visitors | int(11)        | NO   |     | NULL    |                |
| user_id       | int(11)        | NO   | MUL | NULL    |                |
| category_id   | int(11)        | NO   | MUL | NULL    |                |
+---------------+----------------+------+-----+---------+----------------+

然后,有表comment

mysql> desc comment;
+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| comment_id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| comment_content | varchar(600) | NO   |     | NULL    |                |
| comment_date    | datetime     | NO   |     | NULL    |                |
| comment_title   | varchar(300) | NO   |     | NULL    |                |
| user_id         | int(11)      | NO   | MUL | NULL    |                |
| post_id         | int(11)      | NO   | MUL | NULL    |                |
+-----------------+--------------+------+-----+---------+----------------+

您可以在表post_id中看到指向表comment的外键post。 我需要获得下一个结果集:post_id, post_title, post_date, post_summary, number-of-post-comments

我试过这个,但是我没有得到正确的结果:

SELECT 
  p.post_id,
  p.post_date,
  p.post_summary,
  p.post_title,
  COUNT(c.post_id) 
FROM
  post p 
  LEFT JOIN COMMENT c 
    ON p.post_id = c.post_id 

(我不经常使用sql,这对熟悉sql的人来说应该很容易)

1 个答案:

答案 0 :(得分:3)

试试这个

  SELECT 
  p.post_id,
  p.post_date,
  p.post_summary,
  p.post_title,
  COUNT(c.post_id) AS number_of_post_comments 
FROM
  post p 
  LEFT JOIN COMMENT c 
    ON p.post_id = c.post_id 
GROUP BY p.post_id