Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple SQL GROUP BY

Tags:

sql

I have a table named foobar with columns name and location. I want use SQL to get all the names of people that have been to New York but have not been to San Francisco.

So far have:

  select name 
    from foobar 
   where location = "New York" and location != "San Francisco" 
group by name
like image 380
John Avatar asked Jan 29 '26 07:01

John


2 Answers

SELECT f.name
    FROM foobar f
    WHERE f.location = 'New York'
        AND NOT EXISTS(SELECT NULL
                           FROM foobar f2
                           WHERE f2.name = f.name
                               AND f2.location = 'San Francisco')

You could also do this with a LEFT JOIN:

SELECT f.name
    FROM foobar f
        LEFT JOIN foobar f2
            ON f.name = f2.name
                AND f2.location = 'San Francisco'
    WHERE f.location = 'New York'
        AND f2.name IS NULL
like image 58
Joe Stefanelli Avatar answered Jan 30 '26 21:01

Joe Stefanelli


select name 
from foobar 
where location = "New York"
and name not in (select name 
from foobar 
where location = "San Francisco")
like image 23
triclosan Avatar answered Jan 30 '26 20:01

triclosan