How to fetch values of column 1 that contain only the given value of column 2?

别来无恙 提交于 2020-01-06 15:59:15

问题


I want to select names that only appear in Mexico and not in any other country.

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 

The correct query would only return the following names.

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

Any ideas? I'm not sure if this might be a mix of DISTINCT and WHERE conditions.


回答1:


I think you want something like

SELECT Name
FROM <table>
WHERE Country = 'Mexico'
AND Name NOT IN (
    SELECT Name
    FROM <table>
    WHERE Country <> 'Mexico')



回答2:


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



回答3:


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

Script:

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

Output:

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


来源:https://stackoverflow.com/questions/10407415/how-to-fetch-values-of-column-1-that-contain-only-the-given-value-of-column-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!