问题
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