带有外部约束的SQL查询

时间:2013-03-11 21:18:06

标签: mysql foreign-keys

遵循教科书“坚果壳中的SQL”它要求查询

  

对于拥有电子邮件地址的员工,显示其年龄和性别。

在以下数据库中:

CREATE TABLE EMPLOYEES(
   PID SMALLINT NOT NULL,
   PRIMARY KEY(PID),
   CONSTRAINT EMPLOYEES_FK FOREIGN KEY (PID) REFERENCES PERSONS (PID)
);

CREATE TABLE PERSONS(
 PID SMALLINT NOT NULL,
 NAME VARCHAR(20) NOT NULL,
 GENDER CHAR(1) NOT NULL CHECK (GENDER IN ('M','F')),
 AGE SMALLINT NOT NULL CHECK (AGE BETWEEN 0 AND 120),
 BIRTHDATE DATE NOT NULL,
 PRIMARY KEY(PID)
);

CREATE TABLE HASE(
 PID SMALLINT NOT NULL,
 EADDR VARCHAR(30) NOT NULL,
 PRIMARY KEY(PID,EADDR),
 CONSTRAINT HASE_FK FOREIGN KEY (PID) REFERENCES PERSONS (PID)
);

我是SQL查询的新手,所以我的尝试是:

SELECT GENDER, AGE
FROM PERSONS AND EMPLOYEES
WHERE EXISTS HASE.EADDR
;

但我不认为即时通讯与外键有关系。我意识到这是非常基本的,但我认为一旦我看到查询的方式,它将帮助我与其他人。

2 个答案:

答案 0 :(得分:2)

您可以使用EXISTS获取结果

SELECT Gender, Age
FROM Persons
  JOIN Employees ON Persons.PID = Employees.PID
WHERE Exists (SELECT PID
              FROM Hase
              WHERE Persons.PID = Hase.PID)

您也可以使用IN,但EXISTS查询会更快

SELECT Gender, Age
FROM Persons
  JOIN Employees ON Persons.PID = Employees.PID
WHERE Persons.PID IN  (SELECT PID
                       FROM Hase)

答案 1 :(得分:1)

SELECT DISTINCT
  persons.NAME,
  persons.GENDER,
  persons.AGE
FROM
  persons INNER JOIN employees
  ON persons.PID = employees.PID
  INNER JOIN hase
  ON persons.PID = hase.PID

请参阅小提琴here