我目前有2条查询返回
PRODUCER FirstQueryColumn
------------------------------ ----------------------
aaaaaaaaaaaa 1
bbbbbbbbbbb 1
PRODUCER SecondQueryColumn
------------------------------ ----------------------
aaaaaaaaaaaa 2
bbbbbbbbbbb 1
我想知道的是如何进行处理,以便可以在单个查询中获得相同的数据,也就是说,我想要可以产生(的东西Producer, FirstQueryColumn,
SecondQueryColumn)
。
我怎样才能做到这一点?
这是我当前的查询:
select Producers.name Prod, count(Animals.idanimal) AnimalsBought
from AnimalsBought, Animals, Producers
where (AnimalsBought.idanimal = Animals.idanimal) and (Animals.owner = Producers.nif) group by Producers.name;
select Producers.name Prod, count(Animals.idanimal) AnimalsExploration
from AnimalsExploration, Animals, Producers
where (AnimalsExploration.idanimal = Animals.idanimal) and (Animals.owner = Producers.nif) group by Producers.name;
如您所见,在这种情况下,联接不会做很多事情:
select Producers.name Prod, count(AnimalsBought.idanimal) AnimalsBought, count(AnimalsExploration.idanimal) AnimalsExploration
from Producers, Animals, AnimalsBought, AnimalsExploration
where (AnimalsExploration.idanimal = Animals.idanimal) and (Animals.owner = Producers.nif) group by Producers.name;
还是我做错了什么?
我想animals.idanimal
是一个主键。如果是这样,则可以使用左外部联接并count
在要切断的目标列上编写查询NULLs
。
select producers.name prod,
count(animalsbought.idanimal) animalsbought,
count(animalsexploration.idanimal) animalsexploration
from producers
join animals on animals.owner = producers.nif
left join animalsbought on animalsbought.idanimal = animals.idanimal
left join animalsexploration on animalsexploration.idanimal = animals.idanimal
group by producers.name;