如何从三个表中计数?

时间:2019-01-09 01:26:28

标签: mysql sql join mariadb

我有3个表postpost_likepost_comment

我想统计用户的帖子likescomments

帖子:

+-------------+--------------+------+-----+-------------------+----------------+
| Field       | Type         | Null | Key | Default           | Extra          |
+-------------+--------------+------+-----+-------------------+----------------+
| id          | int(30)      | NO   | PRI | NULL              | auto_increment |
| user_id     | int(11)      | NO   |     | 0                 |                |
| description | text         | YES  |     | NULL              |                |
| link        | varchar(100) | YES  |     | ''                |                |

+-------------+--------------+------+-----+-------------------+----------------+

post_like:

+---------+-------------+------+-----+---------+----------------+
| Field   | Type        | Null | Key | Default | Extra          |
+---------+-------------+------+-----+---------+----------------+
| id      | int(11)     | NO   | PRI | NULL    | auto_increment |
| post_id | int(30)     | NO   |     | 0       |                |
| user_id | int(30)     | NO   |     | 0       |                |
| time    | varchar(50) | NO   |     | 0       |                |
+---------+-------------+------+-----+---------+----------------+

post_comment:

+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int(30)      | NO   | PRI | NULL    | auto_increment |
| post_id | int(20)      | NO   |     | 0       |                |
| user_id | int(20)      | NO   |     | 0       |                |
| text    | text         | YES  |     | NULL    |                |
| time    | varchar(100) | NO   |     | 0       |                |
+---------+--------------+------+-----+---------+----------------+

这是我提出的查询:

SELECT 
    p.*,
    COUNT(l.post_id) "likes", 
    COUNT(c.post_id) "comments"
FROM 
    post p
    INNER JOIN post_like l ON p.id = l.post_id 
    INNER JOIN post_comment c ON c.post_id = l.post_id
WHERE 
    p.user_id=55 
GROUP BY 
    l.post_id
ORDER BY
    p.created_at DESC

问题在于查询仅返回一行,而有多个帖子。

我尝试了不同的技巧,研究了类似的问题,但找不到解决方法。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

执行所需操作的快捷方式是使用count(distinct)

SELECT p.id, p.user_id, p.description, p.link,
       COUNT(DISTINCT l.id) as num_likes, 
       COUNT(DISTINCT c.id) as num_comments
FROM post p LEFT JOIN
     post_like l
     ON p.id = l.post_id LEFT JOIN
     post_comment c
     ON p.id = c.post_id
WHERE p.user_id=55 
GROUP BY p.id, p.user_id, p.description, p.link
ORDER BY p.created_at DESC;

更高级的方法是在join之前进行汇总,但是该方法可能适用于您的数据。