使用MS SQL Server,我想计算每个实体相关的实体数量。假设我的架构看起来像这样:
foo (
id UNIQUEIDENTIFIER NOT NULL,
)
thing1 (
id UNIQUEIDENTIFIER NOT NULL
)
thing2 (
id UNIQUEIDENTIFIER NOT NULL
)
thingN (
id UNIQUEIDENTIFIER NOT NULL
)
连接表
foo_thing1 (
foo_id UNIQUEIDENTIFIER NOT NULL,
thing1_id UNIQUEIDENTIFIER NOT NULL
)
等
可能有2个东西,或者10个,或者其他一些数字 - 我想要的东西即使有很多东西也能运作良好。如果只有一个Foo,可能的解决方案如下:
SELECT COUNT(DISTINCT foo_thing1.thing1_id),
COUNT(DISTINCT foo_thing2.thing2_id),
COUNT(DISTINCT foo_thing3.thing3_id),
COUNT(DISTINCT foo_thing4.thing4_id,
FROM foo
LEFT JOIN foo_thing1 ON foo_thing1.thing1_id = thing1.id
LEFT JOIN foo_thing2 ON foo_thing2.thing2_id = thing2.id
LEFT JOIN foo_thing3 ON foo_thing3.thing3_id = thing3.id
LEFT JOIN foo_thing4 ON foo_thing4.thing4_id = thing4.id
GROUP BY foo.id
HAVING foo.id = '12341234-1234-12341234-1234'
但是,我不确定这是否有效。如果Foo与很多东西和很多东西有关,那么我会得到太多的行,然后用DISTINCT隐藏它?
更复杂的是,我实际上想要同时计算多个foo的关系。理想情况下,我想通过任意where子句来完成它,但如果有必要,我可以提供一个id列表,例如WHERE / HAVING foo.id IN(x,y,z)。但是,从那里,我应该如何确定所有的基数? :(
UNION ALL是一个选项,因为我组合这些查询的目的是节省数据库往返延迟。但我怀疑多个SELECT的解析时间意味着它不能 最有效的方式......
答案 0 :(得分:1)
这应该按照你期望的方式工作:
SELECT foo.id,
(SELECT count(*) FROM foo_thing1 WHERE foo_thing1.foo_id = foo.id),
(SELECT count(*) FROM foo_thing2 WHERE foo_thing2.foo_id = foo.id),
(SELECT count(*) FROM foo_thing3 WHERE foo_thing3.foo_id = foo.id),
...
FROM foo
WHERE foo.id IN (1, 2, 3, 7, ...);