【问题标题】:MySQL extending SELECT query with COUNTMySQL 用 COUNT 扩展 SELECT 查询
【发布时间】:2017-10-28 19:38:57
【问题描述】:

我需要一些帮助来创建 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

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

非常感谢您!

【问题讨论】:

  • 提供具体的总和?

标签: mysql select count subquery


【解决方案1】:

我认为以下内容将满足您的需求,但完全有可能提供更有效的解决方案。这会在您的代码中添加一个子查询,该子查询获取每个物种的总数,然后将该总数添加到选择中。我还用更现代和更受欢迎的等价物替换了您的“旧式”JOIN:

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

【讨论】:

  • 哇,这是一个非常快的回复,它绝对完美!非常感谢您,祝您有美好的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 2014-01-18
  • 1970-01-01
相关资源
最近更新 更多