执行此查询的其他方法?
我有以下表格:
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;
但我只是通过反复试验才做到的,而且我发现很难同时推理多个 Animal 表。还有其他方法可以进行此查询吗?或者这是通常的做法?
I have the following tables:
Animals (animal_id, producer_id, ...)
Producers (prod_id, ...)
BoughtAnimals (animal_id (fk), ...)
and I'd like to make a query that tells me for each producer, how many animals it has, and how many of those animals were bought. After much thought, I tried the following approach:
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;
but I did it only by trial and error, and I find it hard to reason about several Animal tables at once. Is there any other approach to make this query? Or is this the usual way of doing it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试这样的事情
Try something like this
使用简单的 JOIN,然后您可以将“COUNT”放入 HAVING 语句中。请参阅 LEFT / INNER JOIN 和 HAVING 的文档,具体取决于您的 SGDB。
Use a simple JOIN, you could then put the "COUNT" in a HAVING statement. See documentation for LEFT / INNER JOIN and HAVING, depending on your SGDB.
我现在忽略生产者表;您需要的所有关键数据都在其他两个表中。一旦这部分正确,您就可以在生产者表上进行内部联接来获取您需要的其他详细信息。
我不清楚最后一列是否更适合命名为“num_bought”或“num_sold”。同样不清楚的是,考虑到某些动物要么被购买,要么被出售,生产者“拥有”动物意味着什么。
I'm ignoring the producers table for now; all the critical data you need is in the other two tables. Once this part is right, you can just do an inner join on the producers table to get the other details you need.
It's not clear to me whether that last column is better named "num_bought" or "num_sold". Also not clear is what it means for a producer to "have" an animal, given that some animals are either bought or sold.