Sql 执行此查询的其他方法?

Sql 执行此查询的其他方法?,sql,database,oracle,Sql,Database,Oracle,我有以下表格: 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

我有以下表格:

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;

但我只是通过反复试验才做到这一点,而且我发现很难同时对几张动物餐桌进行推理。是否有其他方法来进行此查询?或者这是通常的方法吗?

使用一个简单的连接,然后可以将“COUNT”放在HAVING语句中。请参阅关于左/内连接和have的文档,具体取决于您的SGDB。

使用简单连接,然后可以将“COUNT”放在HAVING语句中。根据您的SGDB,请参阅关于左/内连接和have的文档。

尝试类似的方法

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;

试试这样的

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;

我现在忽略生产者表;您需要的所有关键数据都在其他两个表中。一旦这一部分正确,您就可以在producers表上进行内部联接,以获得所需的其他详细信息

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_bunded”还是“num_sell”。考虑到有些动物是买来的还是卖来的,生产者“拥有”动物意味着什么也不清楚。

我现在忽略生产者表;您需要的所有关键数据都在其他两个表中。一旦这一部分正确,您就可以在producers表上进行内部联接,以获得所需的其他详细信息

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_bunded”还是“num_sell”。同样不清楚的是,考虑到有些动物是买卖的,生产者“拥有”动物意味着什么。

我不明白拥有声明在这方面有什么帮助。据我所知,HAVING语句似乎是为了限制返回的行数,而这不是我想要的。我不明白HAVING语句在这方面有什么帮助。据我所知,HAVING语句的目的似乎是限制返回的行数,这不是我想要的。如果停止使用隐式语法并学习连接,您将了解如何更好地执行查询。如果停止使用隐式语法并学习连接,您将了解如何更好地执行查询。