MySQL使用COUNT扩展SELECT查询

时间:2017-05-28 10:57:43

标签: mysql select count subquery

我在创建MySQL查询时需要一些帮助。我们假设我们有一张桌子"动物"包含物种和动物的详细品种。此外,我们有一张表"考试"包含对动物的调查。为了找出被检查的某些品种有多少动物(我们对找到某些品种的检查数量不感兴趣!),我们可以运行这个查询:

SELECT animals.animal_species, 
       animals.animal_breed, 
       Count(DISTINCT animals.animal_id) 
FROM   examinations, 
       animals 
WHERE  examinations.examination_animal_id = animals.animal_id 
       AND animals.animal_breed IS NOT NULL 
GROUP  BY animals.animal_species, 
          animals.animal_breed 
ORDER  BY animals.animal_species 

通过运行这个,我们得到类似的东西:

dog | sheepdog    | 3
dog | collie      | 1
dog | terrier     | 5
cat | Persian cat | 3
cat | Birman cat  | 2

现在我想要包括每个物种的总和。结果应如下所示:

dog | sheepdog    | 3 | 9
dog | collie      | 1 | 9
dog | terrier     | 5 | 9
cat | Persian cat | 3 | 5
cat | Birman cat  | 2 | 5

您能否告诉我如何更改查询以实现此目的?我尝试了几种解决方案,但没有一种解决方案......

提前非常感谢你!

1 个答案:

答案 0 :(得分:1)

我认为以下内容将满足您的需求,但完全有可能提供更有效的解决方案。这会为您的代码添加一个子查询,该子查询获取每个物种的总数,然后将该总数添加到选择中。我也取代了你的老式"加入更现代和首选的等价物:

SELECT
    a.animal_species,
    a.animal_breed,
    COUNT(DISTINCT a.animal_id) as animals_examined,
    species_count.species_animals_examined
    FROM examinations e
JOIN animals a ON
    e.examination_animal_id = a.animal_id
JOIN 
    (SELECT
         a2.animal_species,
         count(distinct a2.animal_id) as species_animals_examined
    FROM examinations e2
    JOIN animals a2 ON
        e2.examination_animal_id = a2.animal_id
    WHERE
        a2.animal_breed IS NOT NULL
    GROUP BY a2.animal_species
    ) as species_count ON
    species_count.animal_species = a.animal_species
WHERE
    a.animal_breed IS NOT NULL
GROUP BY a.animal_species, a.animal_breed
ORDER BY a.animal_species