Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

database - improving the written sql query

I want to write a SQL query for the problem as defined below, my answer is as below, but I am not sure about the answer, can anyone help me? Is the answer correct, or if not, how can I improve it?

Let us consider the following relational schema about physicians and departments:

  • PHYSICIAN (PhysicianId, Name, Surname, Specialization, Gender, BirthDate, Department);

    Let every physician be univocally identified by a code and characterized by a name, a surname, a specialization (we assume to record exactly one specialization for each physician), a gender, a birth date, and the relative department (each physician is assigned to one and only one department).

  • DEPARTMENT (Name, Building, Floor, Chief)

    Let every department be univocally identified by a name and characterized by its location (building and floor) and a chief.

Let us assume that a physician can be the chief of at most one department (the department he/she belongs to). We do not exclude the possibility for two distinct departments to be located at the same floor of the same building.

Define preliminarily primary keys, other candidate keys (if any), and foreign keys (if any). Then, formulate an SQL query to compute the following data (exploiting aggregate functions only if they are strictly necessary):

  • the departments with both male and female physicians, whose physicians are all born after 1955, that is, they are all at most 64 years old.

My answer is as below:

create view table X as {
select d.Name
from department d inner join PHYSICIAN p on 
d.department=f.name
where gender="Female" and gender="Male and birthdate>1955

select *
from X
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your query will not return any records because 'gender' field cannot be equal to Female and Male at the same time. My suggestion is something like:

select distinct d.*
  from departments d
  inner join physicians m on d.name = m.department and m.gender = 'Male'
  inner join physicians f on d.name = f.department and f.gender = 'Female'
  left join physicians o on d.name = o.department and p.birthdate < '1955-01-01'
  where o.id is null

The idea is to find at least one male and one female for each department. After that find one old person for each department and filter out all departments that have such an old person.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...