SQL“GROUP BY”和“INNER JOIN”声明在一起

时间:2018-06-03 17:06:48

标签: mysql sql

我有两张ANIMAL和NEED表:

        ANIMAL                                      NEED        
Name    Species         Birthday                A_Species      Type 
Koala1  Phascolarctidae 02-10-2014           Phascolarctidae    Veg.    
Bear1   Ursinae         03-10-2016           Ursinae            Veg.    
Koala2  Phascolarctidae 04-09-2015           Ursinae            Meet    
Cattle1 Bovidae         20.03.2017           Ursinae            Fish    
Whale1  Cetacea         08.05.2010           Bovidae            Veg.    
                                             Cetacea            Fish    

我想选择下表

    Name    Type                
    Koala1  Veg.                
    Koala2  Veg.                
    Cattle1 Veg.                
    Whale1  Fish                

这是动物及其食物的名单,只需要一种食物!

我必须结合两个

的陈述
SELECT A_Species 
FROM NEED GROUP BY A_Species
HAVING COUNT(A_Species)=1;

SELECT ANIMAL.NAME, NEED.Type 
FROM ANIMAL 
INNER JOIN NEED ON ANIMAL.Species = NEED.A_Species;                 

我试过

SELECT ANIMAL.NAME, NEED.Type 
FROM ANIMAL 
INNER JOIN NEED ON ANIMAL.Species = NEED.A_Species 
WHERE EXISTS(SELECT A_Species 
FROM NEED GROUP BY A_Species
HAVING COUNT(A_Species)=1); 

哪个不行! 你能帮帮我怎样才能把它们放在一起?

1 个答案:

答案 0 :(得分:2)

一种方法使用聚合:

SELECT a.NAME, MAX(n.Type)
FROM ANIMAL a INNER JOIN
     NEED n
     ON a.SPECIES = n.A_SPECIES 
GROUP BY a.Name
HAVING COUNT(*) = 1;

或者替代方法使用NOT EXISTS

SELECT a.NAME, n.Type
FROM ANIMAL a INNER JOIN
     NEED n
     ON a.SPECIES = n.A_SPECIES 
WHERE NOT EXISTS (SELECT 1
                  FROM need n2
                  WHERE n2.A_SPECIES = n.A_SPECIES AND
                        n2.Type <> n.Type
                 );

在实践中,这可能会有更好的表现,尤其是need(a_species, type)上的索引。