返回介绍

solution / 1200-1299 / 1241.Number of Comments per Post / README_EN

发布于 2024-06-17 01:03:21 字数 2912 浏览 0 评论 0 收藏 0

1241. Number of Comments per Post

中文文档

Description

Table: Submissions

+---------------+----------+
| Column Name   | Type   |
+---------------+----------+
| sub_id    | int    |
| parent_id   | int    |
+---------------+----------+
This table may have duplicate rows.
Each row can be a post or comment on the post.
parent_id is null for posts.
parent_id for comments is sub_id for another post in the table.

 

Write a solution to find the number of comments per post. The result table should contain post_id and its corresponding number_of_comments.

The Submissions table may contain duplicate comments. You should count the number of unique comments per post.

The Submissions table may contain duplicate posts. You should treat them as one post.

The result table should be ordered by post_id in ascending order.

The result format is in the following example.

 

Example 1:

Input: 
Submissions table:
+---------+------------+
| sub_id  | parent_id  |
+---------+------------+
| 1     | Null     |
| 2     | Null     |
| 1     | Null     |
| 12    | Null     |
| 3     | 1      |
| 5     | 2      |
| 3     | 1      |
| 4     | 1      |
| 9     | 1      |
| 10    | 2      |
| 6     | 7      |
+---------+------------+
Output: 
+---------+--------------------+
| post_id | number_of_comments |
+---------+--------------------+
| 1     | 3          |
| 2     | 2          |
| 12    | 0          |
+---------+--------------------+
Explanation: 
The post with id 1 has three comments in the table with id 3, 4, and 9. The comment with id 3 is repeated in the table, we counted it only once.
The post with id 2 has two comments in the table with id 5 and 10.
The post with id 12 has no comments in the table.
The comment with id 6 is a comment on a deleted post with id 7 so we ignored it.

Solutions

Solution 1

# Write your MySQL query statement below
WITH
  t AS (
    SELECT DISTINCT s1.sub_id AS post_id, s2.sub_id AS sub_id
    FROM
      Submissions AS s1
      LEFT JOIN Submissions AS s2 ON s1.sub_id = s2.parent_id
    WHERE s1.parent_id IS NULL
  )
SELECT post_id, COUNT(sub_id) AS number_of_comments
FROM t
GROUP BY post_id
ORDER BY post_id;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文