来自另一个表的 SQL 计数列

标签 sql sql-server group-by subquery aggregate-functions

我在一个数据库中有两个表

第一个是 people,它有列

id: int,
name: varchar(10)

还有一个是relationships,代表一种单向跟随

me: int
following: int

mefollowing 是外键,与 people 表中的人的 id 主键相匹配.

我想运行一个查询,给定一个人的 id 返回他们的名字和他们关注的人数以及关注他们的人数。

我目前的尝试是

SELECT *, COUNT(following.me), COUNT(following.following) FROM people
WHERE id = 3
JOIN following f1 on f1.me = id
JOIN following f2 on f2.following = id;

但是它会抛出有关 where 语法的错误。我想我需要在某处使用 group by 但我正在努力解决它如何在多个表上工作。

假设给定 id=2 它将返回 [{name: "sam", followers: 4, following: 3}]

最佳答案

这可以简单地通过内联相关子查询来解决,例如:

select 
    p.name,
    (select count(*) from relationships r where r.following = p.id) followers,
    (select count(*) from relationships r where r.me = p.id) following
from people p
where p.id = 3

这应该是一个非常有效的选择。

否则,从您现有的查询开始,您还可以left join 和聚合:

select 
    p.name,
    count(distinct r.following) followers,
    count(distinct r.me) following
from people p
left join relationships r on p.id in (r.followers, r.me)
where p.id = 2
group by p.id, p.name

关于来自另一个表的 SQL 计数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58572736/

相关文章:

sql - Oracle 虚拟列引用另一个表

sql - postgresql ,当 null 存在时如何递增

sql - 从字符串转换日期和/或时间时转换失败

sql - 如何获取没有任何事件触发器的表列表?

group-by - dask dataframe groupby 导致一个分区内存问题

mysql - 从映射表中获取数据

mysql - 如何决定 GROUP BY 之后保留 JOINED 表中的哪些记录?

sql - mysql limit x, y 等同于SQL Server l?

sql - REFERENCES 带或不带 FOREIGN KEY 有什么区别

sql-server - SQL Server Linux 公共(public)预览版上的 xp_cmdshell