kal*_*ave 2 sql sql-server group-by subquery aggregate-functions
我的数据库中有两个表
第一个是people
有列的
id: int,
name: varchar(10)
Run Code Online (Sandbox Code Playgroud)
另一个relationships
代表单向跟随的存在
me: int
following: int
Run Code Online (Sandbox Code Playgroud)
其中me
和是与 table 中 person 的主键following
匹配的外键。id
people
我想运行一个查询,给定一个id
人,返回他们的姓名、他们关注的人数以及关注他们的人数。
我目前的尝试是
id: int,
name: varchar(10)
Run Code Online (Sandbox Code Playgroud)
但它引发了有关 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
Run Code Online (Sandbox Code Playgroud)
这应该是一个非常有效的选择。
否则,从现有查询开始,您还可以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
Run Code Online (Sandbox Code Playgroud)