如何使用SQL group从一个标准中获取多个字段?

时间:2015-03-16 10:00:35

标签: sql mysqli

此查询可能返回错误的名称,因为我要查询的名称是每个物种中最小的动物。我怎样才能得到正确的a.name

SELECT 
a.name,
MIN(a.size)

FROM animal a
LEFT JOIN species s ON s.idSpecies = a.idAnimal

GROUP BY s.id

3 个答案:

答案 0 :(得分:1)

这方面的一种方法是首先找到每个物种最小的动物大小(正如你所做的那样),虽然我假设物种永远不会因为动物必须属于一个物种而无效,但它也不需要此时加入物种:

SELECT  a.IDSpecies, MIN(a.Size) AS Size
FROM    Animal AS a
GROUP BY a.IDSpecies

现在,您可以将此查询的结果返回到主查询以过滤结果。

SELECT  a.Name AS AnimalName,
        a.Size,
        s.Name AS SpeciesName
FROM    Animal AS a
        INNER JOIN Species AS s
            ON s.ID = a.IDSpecies
        INNER JOIN
        (   SELECT  a.IDSpecies, MIN(a.Size) AS Size
            FROM    Animal AS a
            GROUP BY a.IDSpecies
        ) AS ma
            ON ma.IDSpecies = a.IDSpecies
            AND ma.Size = a.Size;

另一种方法是使用NOT EXISTS

SELECT  a.Name AS AnimalName,
        a.Size,
        s.Name AS SpeciesName
FROM    Animal AS a
        INNER JOIN Species AS s
            ON s.ID = a.IDSpecies
WHERE   NOT EXISTS
        (   SELECT  1
            FROM    Animal AS a2
            WHERE   a2.IDSpecies = a.IDSpecies
            AND     a2.Size < a.Size
        );

所以你从简单的选择开始,然后使用NOT EXISTS去除任何动物,同一物种中存在较小的动物。

由于MySQL将optimize LEFT JOIN/IS NULL better than NOT EXISTS,因此在MySQL中编写查询的更好方法是:

SELECT  a.Name AS AnimalName,
        a.Size,
        s.Name AS SpeciesName
FROM    Animal AS a
        INNER JOIN Species AS s
            ON s.ID = a.IDSpecies
        LEFT JOIN Animal AS a2
            ON a2.IDSpecies = a.IDSpecies
            AND a2.Size < a.Size
WHERE   a2.ID IS NULL;

概念与<{1}}完全相同,但不需要相关的子查询。

答案 1 :(得分:0)

按照分组依据的简单示例:

SELECT C.CountryName Country, SN.StateName,  COUNT(CN.ID) CityCount 
FROM Table_StatesName SN 
JOIN Table_Countries C ON C.ID = SN.CountryID
JOIN Table_CityName CN ON CN.StateID = SN.ID
GROUP BY C.CountryName,  SN.StateName  ORDER BY SN.StateName

输出:

Country         StateName                       CityCount

Australia       Australian Capital Territory    219
Australia       New South Wales                 2250
Australia       Northern Territory              218
Australia       Queensland                      2250
Australia       South Australia                 1501
Australia       Tasmania                        613
Australia       Victoria                        2250

答案 2 :(得分:0)

获取size =最小尺寸的所有行。使用相关子查询来查找最小的大小:

SELECT *
FROM animal a
  LEFT JOIN species s ON s.idSpecies = a.idAnimal
where a.size = (select min(a2.size)
                from animal a2
                  LEFT JOIN species s2 ON ss.idSpecies = as.idAnimal
                where s.id = s2.id)