If groupby does not meet the condition, no data is returned.

Source: Internet
Author: User
If groupby does not meet the condition, he does not return data, for example, posts Post table.
Create table posts (
Posts_id,
Forumid, (Forum ID)
Posts_title,
Posts_postTime,
)

Comments comment table
Create table comments (
Comments_id,
Postsid,
Comments_content,
Comments_postTime,
)

The result is: read all posts with Forum ID 1 and count the total number of comments for each post.
I use count (comments_id) AS commentsNum to count comments. However, if no comments are posted in the comments table, group by ignores the comments.
Posts_id forumid commentsNum
1 1 4
2 1 5
3 1 4
4 1 0
I want to return 0 or Null when The Post has no comment in the comment table. how can this problem be solved?


Reply to discussion (solution)

Select. posts_id,. forumid, count (B. comments_id) as commentsNum from posts a left join comments B on. posts_id = B. postsidgroup by B. postsid having. forumid = 1

Solved the problem. thanks to the moderator, Having was not used =

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.