我的目标是返回员工居住在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子句中,只有那些雇员才能在两个城市居住?
谢谢!
答案 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
)
这可能有用。