使 SELECT 子查询 COUNT 个订阅者的总订阅者
Make SELECT subquery COUNT the total subscribers of a subscriber
我正在尝试创建一个查询来计算一个订阅者的订阅者总数。目前看起来像这样:
await this.queryInstance.query(
'SELECT all_users_subbed_to.* , (SELECT COUNT(??????)) AS subscribers_sub_count
FROM
(SELECT publisher_id, subscriber_id, u2.username
AS username, u2.user_photo AS user_photo
FROM subscribers s
INNER JOIN users u
ON (u.id = s.subscriber_id)
INNER JOIN users u2 ON (u2.id = s.publisher_id)
WHERE subscriber_id = ()
LIMIT 20
OFFSET ())
AS all_users_subbed_to;'
,
[currentUserId = 80, offset]
);
FROM 子句又名 all_users_subbed_to
工作正常并显示当前用户拥有的所有订阅者。数据返回如下:
"subscribedToCurrentUser": [
{
"publisher_id": 84,
"subscriber_id": 80,
"username": "supercoookie",
"user_photo": "profile-pic-for-supercoookie.jpeg"
},
{
"publisher_id": 88,
"subscriber_id": 80,
"username": "GERPAL1",
"user_photo": "profile-pic-for-GERPAL1.jpeg"
}
]
我遇到的问题是获取这些订阅者列表的订阅者总数。我需要使用订阅者 publisher_id 即 all_users_subbed_to.publisher_id
并从订阅者 table 获取他们的订阅总数(使用 COUNT)。我想创建一个名为 have subscribers_sub_count
的新列,其中包含该总数。
有任何想法吗?
它应该是这样的:
"subscribedToCurrentUser": [
{
"publisher_id": 84,
"subscriber_id": 80,
"username": "supercoookie",
"user_photo": "profile-pic-for-supercoookie.jpeg",
"subscribers_sub_count": 3
},
{
"publisher_id": 88,
"subscriber_id": 80,
"username": "GERPAL1",
"user_photo": "profile-pic-for-GERPAL1.jpeg",
"subscribers_sub_count": 70
}
]
订阅者 table 看起来像这样:
await this.queryInstance.query(
'SELECT all_users_subbed_to.*, COUNT(all_users_subbed_to.id) AS subscribers_sub_count
FROM
(SELECT publisher_id, subscriber_id, u2.username
AS username, u2.user_photo AS user_photo
FROM subscribers s
INNER JOIN users u
ON (u.id = s.subscriber_id)
INNER JOIN users u2 ON (u2.id = s.publisher_id)
WHERE subscriber_id = ()
LIMIT 20
OFFSET ())
AS all_users_subbed_to;'
,
[currentUserId = 80, offset]
);
已修复。它只需要一个使用来自 all_users_subbed_to
await this.queryInstance.query(
'SELECT all_users_subbed_to.* ,
(SELECT COUNT(*) FROM subscribers s2 WHERE s2.publisher_id = all_users_subbed_to.publisher_id) AS subscribers_sub_count AS subscribers_sub_count
FROM
(SELECT publisher_id, subscriber_id, u2.username
AS username, u2.user_photo AS user_photo
FROM subscribers s
INNER JOIN users u
ON (u.id = s.subscriber_id)
INNER JOIN users u2 ON (u2.id = s.publisher_id)
WHERE subscriber_id = ()
LIMIT 20
OFFSET ())
AS all_users_subbed_to;'
,
[currentUserId = 80, offset]
);