时间:2016-03-16 14:57:38

标签: mysql sql performance select group-by

我有一个动物园。

动物园表

id | name | 

动物表

id | zoo_id | name |    type
1     1       Horse      0
2     1       Elephant   0   
3     1       Parrot     1
4     2       Whale      2     
5     2       Fox        0
6     1       Snake      3

我想选择所有动物园数据以及该动物园的动物总数该动物园中存在的所有动物类型

的MySQL

SELECT zoo.id as zooid,zoo.name,
(SELECT COUNT(*) FROM animal WHERE animal.zoo_id = zoo.id) as total_animals
 FROM zoo;

但是我怎么能够在那个动物园里存在 的所有动物类型

预期结果

zooid | name |  total | available_types
 1      USAZOO   4        0 1 3    
 2      UKZOO    2        0 2     

因为我要选择很多动物园因此性能很重要

2 个答案:

答案 0 :(得分:1)

您可以使用GROUP_CONCAT:

SELECT zoo.id as zooid,zoo.name,
       (SELECT COUNT(*) FROM animal WHERE animal.zoo_id = zoo.id) as total_animals,
       group_concat(type separator ' ')
FROM zoo
GROUP BY zoo.id,zoo.name

我认为你也需要这个动物园的名字,你是如何得到你的名字结果的?无论如何 -

SELECT zoo.id as zooid,
       group_concat(zoo.name separator ' ') as zoo_name,
       (SELECT COUNT(*) FROM animal WHERE animal.zoo_id = zoo.id) as total_animals,
       group_concat(type separator ' ')
FROM zoo
GROUP BY zoo.id

你应该通过加入来做到这一点:

SELECT zoo.id as zooid,
       group_concat(zoo.name separator ' ') as zoo_name,
       COUNT(*) as total_animals,
       group_concat(type separator ' ')
FROM zoo
INNER JOIN animals
 ON animal.zoo_id = zoo.id
GROUP BY zoo.id

答案 1 :(得分:0)

完善sagi的答案:

SELECT Zoo.id as zooid, zoo.name AS name,
       COUNT(*) AS total,
       GROUP_CONCAT(DISTINCT type separator ' ') AS available_types
FROM Zoo
INNER JOIN Animal
 ON Animal.zoo_id = zoo.id
GROUP BY zoo.id

这只给你了不同类型的动物。你可以在这里玩:SQLFiddle