如何获取仅包含第2列给定值的第1列的值?

时间:2012-05-02 03:43:44

标签: sql join distinct where-clause

我想选择出现在墨西哥而非其他任何国家/地区的名称。

Country      |  Name      
-------------|------------
Mexico       |  Vallejo
Mexico       |  Rachel
United States|  Rachel
UK           |  Rachel
Australia    |  Rachel
Mexico       |  Amy
Canada       |  Amy 
Mexico       |  Annette
Mexico       |  Jennifer
Swahili      |  Jennifer 
Mexico       |  Benedict 

正确的查询只会返回以下名称。

Name      
---------
Annette
Benedict
Vallejo

有什么想法吗?我不确定这可能是DISTINCT和WHERE条件的混合。

3 个答案:

答案 0 :(得分:2)

SELECT 
      Name 
  FROM table 
  WHERE Name NOT IN 
  (
    SELECT DISTINCT 
          Name 
        FROM table 
        WHERE Country != 'Mexico'
  )

答案 1 :(得分:1)

我想你想要像

这样的东西
SELECT Name
FROM <table>
WHERE Country = 'Mexico'
AND Name NOT IN (
    SELECT Name
    FROM <table>
    WHERE Country <> 'Mexico')

答案 2 :(得分:1)

Click here to view the demo in SQL Fiddle using MySQL.

脚本:

CREATE TABLE mytable
(
    country VARCHAR(30) NOT NULL
  , name    VARCHAR(30) NOT NULL
);

INSERT INTO mytable (country, name) VALUES
 ('Mexico',         'Vallejo'),
 ('Mexico',         'Rachel'),
 ('United States',  'Rachel'),
 ('UK',             'Rachel'),
 ('Australia',      'Rachel'),
 ('Mexico',         'Amy'),
 ('Canada',         'Amy '),
 ('Mexico',         'Annette'),
 ('Mexico',         'Jennifer'),
 ('Swahili',        'Jennifer'),
 ('Swahili',        'Steve'),'),
 ('Swahili',        'Jill'),
 ('Mexico',         'Benedict');

SELECT      name
FROM        mytable
GROUP BY    name
HAVING      AVG((CASE WHEN country = 'Mexico' THEN 1 ELSE 0 END) * 1.) >= 1

输出

NAME
--------
Annette
Benedict
Vallejo