SQL查询没有产生正确的结果

时间:2013-09-22 20:42:47

标签: sql oracle where natural-join

以下SQL查询的目标是返回居住在San Fran或LA的每位女经理的姓名和工资。我很困惑为什么这个查询返回男性经理以及女性经理...我原本以为定义约束“gender ='F'”以及自然联接将会摆脱所有男性经理立即上市。

select Lastname, FirstName, MidInitial, salary, gender
  from Employee natural join Works natural join Manages
where Lastname = ManagerLastname and
FirstName = MFirstName and
MidInitial = MMidInitial and
gender = 'F' and
city = 'San Fran' or city = 'LA';

--RESULT:
LASTNAME    FIRSTNAME   MIDINITIAL  SALARY  GENDER
Brandy      Dan         L           42000   M
Clemson     Ann         M           39000   F
Gill        Mary        L           48700   F
Simon       Eric        K           45000   M

有没有人看到上述查询的任何内在错误?仅供参考:以下是此数据库表格的架构:

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 company(
    company_name    varchar(20),
    city    varchar(10),
    primary key(company_name));

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

create table Manages(
    Lastname    varchar(10),
    FirstName   varchar(10),
    MidInitial  char(1),
    ManagerLastname varchar(10),
    MFirstName  varchar(10),
    MMidInitial char(1),
    start_date  date,
    primary key(Lastname, FirstName, MidInitial, ManagerLastname, MFirstName, MMidInitial),
    foreign key(Lastname, FirstName, MidInitial) references Employee);

另外,我正在使用SQL for Oracle 11g R2。

谢谢你看看这个!

1 个答案:

答案 0 :(得分:2)

问题是AND的优先级高于OR

所以你的查询实际上说:

  

显示 Lastname = ManagerLastname FirstName = MFirstName MidInitial = MMidInitial gender ='F'<的所有记录/ strong>和 city ='San Fran'

- 或 -

  

city ='LA'

你想要的是:

where Lastname = ManagerLastname and
FirstName = MFirstName and
MidInitial = MMidInitial and
gender = 'F' and
( city = 'San Fran' or city = 'LA' )