我有三张table post
, post_like
以及 post_comment
.
我想数数 likes
以及 comments
用户的帖子数量:
职位:
+-------------+--------------+------+-----+-------------------+----------------+
| 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 | | '' | |
+-------------+--------------+------+-----+-------------------+----------------+
发布类似:
+---------+-------------+------+-----+---------+----------------+
| 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 | |
+---------+-------------+------+-----+---------+----------------+
发布评论:
+---------+--------------+------+-----+---------+----------------+
| 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
问题是查询只返回一行,而有几个post。
我尝试过不同的技巧,也研究过类似的问题,但都找不到解决办法。
我该怎么修?
1条答案
按热度按时间pxy2qtax1#
做你想做的事的快捷而肮脏的方法是使用
count(distinct)
:更先进的方法是在你面前聚集
join
,但此方法可能适用于您的数据。