I have multiple tables with some foreign keys in some. Here are the tables;

Doctor
Doctor_id, FirstName, SecondName,etc...

Hospital
Hospital_id, Name...

Job
Job_id
fk Doctor_id
fk Hospital_id

I'm trying to show a list of doctors that works in 'X' hospital. How would I run this query?

SELECT FirstName, SecondName
FROM Doctor, Job, Hospital
WHERE Hospital.Name = 'HospitalName' AND Job.hospital_id = Hospital.hospital_id;

I'm not sure if that particular query is right because it shows every single doctor (not the ones that work in 'HospitalName'. If that is correct than I guess the foreign keys ain't right?

Thanks in advance. DG

有帮助吗?

解决方案 2

You are missing one join condition.

SELECT FirstName, SecondName
FROM Doctor, Job, Hospital
WHERE Hospital.Name = 'HospitalName' 
AND Job.hospital_id = Hospital.hospital_id
AND job.Doctor_id = Doctor.doctor_id;

其他提示

You should learn to use proper join syntax. Then mistakes like this are much less likely to occur:

SELECT d.FirstName, d.SecondName
FROM Doctor d join
     Job j
     on d.Doctor_id = j.Doctor_Id join
     Hospital h
     on j.hospital_id = h.hospital_id
WHERE h.Name = 'HospitalName';

This also adds in table aliases for every column, so someone reading the query knows where they are coming from.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top