我的例子有点愚蠢,但我想到的是最好的;)
Zoo
===
Id
Name
Animal
=======
Id
Species
ZooId
Zookeeper
=========
Id
FullName
ZooId
有以下行:
Zoo
===
1, New York
2, Berlin
Animal
======
1, Tiger, 1
2, Monkey, 1
3, Bear, 1
4, Tiger, 2
5, Zebra, 2
Zookeeper
=========
1, John Doe, 1
2, Peter Smith, 2
3, Ronald Jackson, 2
4, Michael Miller, 2
我的预期输出应该是:
New York, 3, 1
Berlin, 2, 3
我尝试了以下查询,但这是无稽之谈。
SELECT Zoo.Name, COUNT(Animal.Id) AS Animals, COUNT(Zookeeper.Id) AS Zookeepers
FROM Zoo
LEFT JOIN Animal ON Animal.ZooId = Zoo.Id
LEFT JOIN Zookeper ON Zookeeper.ZooId = Zoo.Id
GROUP BY Zoo.Name
两列的计数相同,即使是小型数据集也需要几分钟。