【问题标题】:how to count values with using find_in_set?如何使用 find_in_set 计算值?
【发布时间】:2011-08-31 12:32:26
【问题描述】:

在我的数据库中,uid 是自动增量值,表示用户 id,u_follow 显示使用 uid 分隔的逗号跟随其他用户的用户。我想计算每个用户有多少关注者。我该怎么做?

uid        u_follow
1          2,3
2          1,3
3          1,2
4          NULL
5          2,3,4

【问题讨论】:

  • 你能在你的脚本中做到这一点吗?如果可能的话,我会建议对数据进行规范化。
  • 规范化数据是什么意思?
  • E 先生关于总结的回答。看看那个。

标签: mysql sql count csv


【解决方案1】:

每列存储一个值,否则您将无法进行关系查询。有关数据库规范化的介绍,请参阅this excellent discussion

users

uid
...

followers

uid u_follow
1   2
1   3
2   1
2   3
3   1
3   2
5   2
5   3
5   4

然后:

select u_follow, count(*) as num_followers from followers group by u_follow

如果您想包含没有关注者的用户,请执行以下操作:

with a as (
  select u_follow, count(*) as num_followers
  from followers group by u_follow
)
select users.uid, coalesce(a.num_followers,0)
from users outer join a on users.uid = a.u_follow

【讨论】:

    猜你喜欢
    • 2012-12-02
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 2017-11-24
    • 1970-01-01
    相关资源
    最近更新 更多