MySql - 在不使用任何聚合函数的情况下查找至少发生两次的值

时间:2014-08-21 19:21:10

标签: mysql sql database

表:的城市

City_Name (PK)    State_Name (PK)    Population
--------------    ---------------    ----------
Austin            MA
Austin            TX
Burlington        VT
Fresno            CA
Houston           TX
Independence      KS
Independence      MO
Independence      PA 
Kansas            CA 
Kansas            MO
Paris             MO 
Paris             OR 
Paris             TX 
Paris             VA  
Paso              TX

上表有一个复合主键(City_Name和State_Name)。我想找到至少发生在两个不同国家的城市。在这种情况下,结果将是

City_Name
---------
Austin
Independence
Kansas
Paris

其他城市不符合条件,因为它们至少在两个州都没有。

该解决方案是练习关系演算问题所必需的,因此(不幸的是)不能使用诸如COUNT()之类的聚合函数。我浏览了一本数据库书,在那里我看到了类似问题的解决方案,看起来像这样,但没有用。

SELECT c1.State_Name FROM City AS c1
JOIN City AS c2 on c1.City_Name = c2.City_Name AND c1.State_Name = c2.State_Name
JOIN City AS c3 on c1.City_Name = c3.City_Name AND c1.State_Name = c3.State_Name
WHERE (c2.City_Name<>c3.City_Name) AND (c2.State_Name<>c3.State_Name);

此时的一些帮助将非常受欢迎。

5 个答案:

答案 0 :(得分:5)

您可以使用COUNT(DISTINCT)并使用HAVING子句限制结果:

SELECT City_Name, COUNT(DISTINCT State_Name)
FROM City
GROUP BY City_NAME
HAVING COUNT(DISTINCT State_Name) > 1

请参阅COUNT(DISTINCT)

的文档
  

返回具有不同非NULL expr值的行数。

我忽略了无法使用COUNT()的限制。这确实导致了自我加入:

SELECT
    DISTINCT c1.City_Name
FROM
    City c1
INNER JOIN
    City c2
ON
    c1.City_Name = c2.City_Name
AND
    c1.State_Name <> c2.State_Name

Demo两种解决方案。

答案 1 :(得分:4)

如果您不能使用任何类型的聚合函数,那么以下内容将返回至少出现两次的城市

SELECT distinct c1.city_name 
  FROM `city` c1 
  JOIN city c2 
        ON c1.city_name=c2.city_name 
       AND c1.state_name!=c2.state_name

我认为不仅COUNT而且任何类型的aggegate都不可用

答案 2 :(得分:1)

SELECT City_Name FROM City GROUP BY City_Name HAVING COUNT(City_Name) > 1;

答案 3 :(得分:1)

您可以使用exists子查询:

select  city_name 
from    city c1
where   exists 
        (
        select  *
        from    city c2
        where   c1.city_name = c2.city_name 
                and c1.state_name <> c2.state_name
        )

答案 4 :(得分:0)

SELECT city FROM mytable
GROUP BY city
HAVING count(city) > 1

<强> SQLFiddle Demo