1

我有这个代码,我用它来获取订阅者的数量:

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

4

3 回答 3

1

试试这个:

SELECT
  p.provider_id,
  provider.name,
  subcat_id,
  COUNT(user_id) AS subscribers 
FROM subscribers s
JOIN provider p ON p.provider_id = s.provider.id
WHERE subcat_id = 5
GROUP BY 1, 2, 3
ORDER BY 4 DESC 
LIMIT 10

注意使用:

  • 表的别名,以便更清晰地区分常见的列名,
  • group by 列出所有非聚合列(您当前的查询将无法正常工作)
于 2013-08-09T15:45:45.543 回答
0

不太确定你的代码是什么,但你需要做的是......假设你有表 A 和表 B。我猜 Provider_id 是你的链接 ID

    Select TableA.provder_id,
    TableB.subcat_id,
    TableA.Name,
    Count(user_id) as subscribers)
    FROM TableA
    INNER JOIN TableB
    ON TableB.provder_id = TableA.provider_id
WHERE subcat_id = 5
GROUP BY TableA.Provider_id,
TableB.Provider_id,
TableA.Name

当您使用“计数”时,您需要对所有字段进行分组

于 2013-08-09T15:41:46.950 回答
0

这将为您解决问题:

SELECT provider_id,provider.name, subcat_id, COUNT(user_id) AS subscribers 
FROM subscribers 
JOIN provider ON provider_id = provider.id
WHERE subcat_id=5 
GROUP BY provider_id 
ORDER BY subscribers DESC 
LIMIT 10 
于 2013-08-09T15:43:22.870 回答