MySQL在SELECT语句中分组

时间:2014-03-18 06:09:34

标签: mysql grouping

我有一张桌子“动物”

table animals

我想弄清楚这两类动物有多少: 爬行动物:海龟,鳄鱼,蜥蜴,蛇 和 啮齿动物:仓鼠,豪猪,睡鼠,水豚

当我为一个类别写作时:

SELECT Reptiles
FROM    (Select distinct COUNT(an_id) as Reptiles
         from animals
         Where an_type in ('chelonian', 'crocodilian', 'lizard', 'snake'))rep;

我得到了正确答案:

爬行动物= 9

然后我想添加第二列Rodents,所以我写道:

SELECT Reptiles, Rodents
FROM    (Select distinct COUNT(an_id) as Reptiles
        from animals
        Where an_type in ('chelonian', 'crocodilian', 'lizard', 'snake'))rep
            (Select distinct count(an_id) as Rodents
            from animals
            where an_type in ('hamster', 'porcupine', 'dormouse', 'capybara'))rod
;

当然我收到语法错误。

我只想拥有两列爬虫和啮齿动物的动物数量(an_id)。 有人能告诉我写这个查询的正确方法吗?

提前谢谢你,

嘀嘀

2 个答案:

答案 0 :(得分:1)

您在分离表格时错过了逗号(,)

  

(&#39; chelonian&#39;,#39; crocodilian&#39;,&#39; lizard&#39;,&#39; snake&#39;)中的an_type)代表   <强>,               (选择不同的计数(an_id)作为啮齿动物

试试这个

SELECT Reptiles, Rodents
FROM 
    (
     Select distinct COUNT(an_id) as Reptiles
     From animals
     Where an_type in ('chelonian', 'crocodilian', 'lizard', 'snake')
    ) rep,
    (
     Select distinct count(an_id) as Rodents
     from animals
     where an_type in ('hamster', 'porcupine', 'dormouse', 'capybara')
    )rod

答案 1 :(得分:1)

在此行上方缺少逗号(,)?

(Select distinct count(an_id) as Rodents