简单的SQL GROUP BY

Joh*_*ohn 2 sql

我有一个以foobarname和列命名的表location.我想用SQL来获取去过纽约但没去过旧金山的所有人的名字.

到目前为止:

  select name 
    from foobar 
   where location = "New York" and location != "San Francisco" 
group by name
Run Code Online (Sandbox Code Playgroud)

Joe*_*lli 7

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')
Run Code Online (Sandbox Code Playgroud)

您也可以使用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
Run Code Online (Sandbox Code Playgroud)


tri*_*san 5

select name 
from foobar 
where location = "New York"
and name not in (select name 
from foobar 
where location = "San Francisco")
Run Code Online (Sandbox Code Playgroud)