我有这个代码,我用它来获取订阅者的数量:
SELECT provider_id,subcat_id, COUNT(user_id) AS subscribers
FROM subscribers WHERE subcat_id=5
AND provider_id=provider_id
GROUP BY provider_id
ORDER BY subscribers DESC LIMIT 10
provider_id
是提供者表的外键,其中包含provider_name
.
如何获得获取 provider_id 的外键值并将其替换为表提供者的 provider_name 的结果?我尝试了内部连接,但没有成功。这可能是语法错误,因为我的选择查询有点复杂。
我现在得到的结果是:
+----------+---------+-----------+
|provder_id|subcat_id|subscribers|
+----------+---------+-----------+
|2 |5 |5 |
+----------+---------+-----------+
|4 |5 |3 |
+----------+---------+-----------+
|1 |5 |1 |
+----------+---------+-----------+
但是,我想要的是:
+----------+-------------+---------+-----------+
|provder_id|provider_name|subcat_id|subscribers|
+----------+-------------+---------+-----------+
|2 |Alex |5 |5 |
+----------+-------------+---------+-----------+
SELECT subscribers.provider_id,subscribers.subcat_id, COUNT(user_id) AS 订阅者 FROM 订阅者 JOIN provider ON subscribers.provider_id=providers.provider_name WHERE subscribers.subcat_id=5 AND subscribers.provider_id=subscribers.provider_id GROUP BY subscribers.provider_id ORDER BY subscribers DESC限制 10
那行不通
解决了
SELECT s.provider_id,p.provider_name, s.subcat_id, COUNT(s.user_id) AS 订阅者 FROM 订阅者 s 加入提供者 p ON s.provider_id=p.provider_id WHERE s.subcat_id=5 AND s.provider_id=s.provider_id GROUP BY provider_id ORDER BY 订阅者 DESC LIMIT 10