My goal is to return a list of the names of companies that have employees living in both San Fran and LA. Here is my query so far, along with the schema:

select distinct company_name
  from Works natural join Employee
where city = 'San Fran' or city = 'LA';

create table Employee(
    Lastname    varchar(10),
    FirstName   varchar(10),
    MidInitial  char(1),
    gender      char(1),
    street      varchar(10),
    city        varchar(10),
    primary key(Lastname, FirstName, MidInitial));

create table Works(
    Lastname    varchar(10),
    FirstName   varchar(10),
    MidInitial  char(1),
    company_name    varchar(20),
    salary      numeric(8,2),
    primary key(Lastname, FirstName, MidInitial, company_name),
    foreign key(Lastname, FirstName, MidInitial) references Employee,
    foreign key(company_name) references company);

I understand that right now, my query is returning a list of all the companies with employees that either live in San Fran or LA, or both... What would be the way to go about using both an AND and an OR on the where clause so as to get only the companies that have employees living in BOTH cities?

Thanks!

有帮助吗?

解决方案

What you want is the natural intersection of these two subsets. Here is the SQL to acheive this :)

select distinct company_name
  from Works natural join Employee
where city = 'San Fran';
intersect
select distinct company_name
  from Works natural join Employee
where city = 'LA';

其他提示

select distinct company_name
from Works natural join Employee
where city = 'San Fran'
and company_name in 
(
    select company_name
    from Works w natural join Employee e
    where city = 'LA'
    group by company_name
)

This might work.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top