不确定此SQL查询的where子句

时间:2013-09-18 11:39:50

标签: sql where relational-division

我的目标是返回员工居住在San Fran和LA的公司名单。到目前为止,这是我的查询以及架构:

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);

我理解,现在,我的查询返回了所有员工的列表,这些公司的员工要么住在San Fran或LA,要么两者都有......将AND和OR一起使用的方法是什么?在where子句中,只有那些雇员才能在两个城市居住?

谢谢!

2 个答案:

答案 0 :(得分:2)

你想要的是这两个子集的自然交集。以下是实现此目的的SQL:)

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';

答案 1 :(得分:1)

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
)

这可能有用。