2011-02-02 102 views
0

我有以下表格:执行此查询的其他方法?

Animals (animal_id, producer_id, ...) 
Producers (prod_id, ...) 
BoughtAnimals (animal_id (fk), ...) 

,我想提出一个查询,告诉我每一个制片人,有多少动物了,而有多少动物被买走。左思右想,我尝试以下方法:

select Producers.name, count (distinct A1.animal_id), count(distinct BoughtAnimals.animal_id) 
from Producers, Animals A1, Animals A2, BoughtAnimals 
where 
    Producers.nif = A1.producer_id and 
    Producers.nif = A2.producer_id and 
    BoughtAnimals.animal_id = A2.animal_id 
group by Producers.name; 

,但我只能通过试验和错误做了,我觉得很难推论几种动物的表一次。有没有其他的方法来做这个查询?或者这是通常的做法吗?

+2

如果停止使用隐式语法并了解连接,您将会更好地理解如何更好地进行查询。 – HLGEM 2011-02-03 18:11:18

回答

1

使用简单的JOIN,您可以将“COUNT”放在HAVING语句中。请参阅LEFT/INNER JOIN和HAVING的文档,具体取决于您的SGDB。

+0

我不明白HAVING语句将如何帮助解决此问题。根据我读过的内容,似乎HAVING语句提供了限制返回的行数的目的,这不是我正在寻找的目的。 – 2011-02-03 07:39:41

3

尝试这样的事情

select p.name, 
    sum(case when ba.anyfield is not null then 1 else 0 end) bought_count, 
    count(1) total_count 
from Producers p join Animals a on (p.nif = a.producer_id) 
    left join BoughtAnimals ba using (animal_id) 
group by p.name; 
0

我忽略了生产商表现;您需要的所有关键数据都在另外两张表格中。一旦这部分是正确的,你可以在生产者表上做一个内部连接来获得你需要的其他细节。

select a1.producer_id, 
     count(a1.animal_id) as num_animals, 
     count(b1.animal_id) as num_bought 
from animals a1 
left join boughtanimals b1 on (b1.animal_id = a1.animal_id) 
group by producer_id; 

我不清楚最后一列是否更好地命名为“num_bought”或“num_sold”。对于生产者来说,“拥有”动物的含义也不明确,因为有些动物是被买卖的。