具有多个连接的MySQL查询

时间:2014-05-14 12:21:25

标签: mysql

我想获得以下信息:

所有囚犯的prisoner_id,first_name,last_name,job_description,即使他们没有工作

从表格中:

Work:
Prisoner_id
job_id
start_date

Job:
job_id
job_description

Prisoner:
Prisoner_id
person_ssn

Person:
person_ssn
first_name
last_name

这是我的尝试,但我不知道如何获得工作描述。

select prisoner_id, first_name, last_name, job_description from
prisoner
left join work on prisoner_id
natural join person on person_ssn;

6 个答案:

答案 0 :(得分:1)

试试这个

select pr.Prisoner_id,
p.first_name,
p.last_name,
j.job_description
from prisoner pr
left join work w on pr.Prisoner_id = w.Prisoner_id
left join job j on w.job_id = j.job_id
inner join person p on pr.person_ssn = p.person_ssn

答案 1 :(得分:1)

假设囚犯总是在人员表上有记录: -

SELECT prisoner.prisoner_id, 
    person.first_name, 
    person.last_name, 
    job.job_description 
FROM prisoner
INNER JOIN person on prisoner.person_ssn = person.person_ssn
LEFT OUTER JOIN work on prisoner.prisoner_id = work.prisoner_id
LEFT OUTER JOIN job ON work.job_id = job.job_id;

避免使用自然连接。

答案 2 :(得分:0)

试试这个:

SELECT w.prisoner_id, p.first_name, p.last_name, j.job_description FROM WORK w LEFT JOIN 
prisoner pr ON w.prisoner_id=pr.prisoner_id LEFT JOIN person p ON    
p.person_ssn=pr.person_ssn
LEFT JOIN Job j ON w.job_id=j.job_id

答案 3 :(得分:0)

select prisoner_id, first_name, last_name, job_description from
prisoner left join work on work.prisoner_id = prisoner.prisoner_id    
natural join person on person.person_ssn = prisoner.person_ssn
natural join job on work.job_id =job.job_id

答案 4 :(得分:0)

试试这个,

select p.prisoner_id, per.first_name, per.last_name, j.job_description
from person per, prisoner p, work w left join job on w.job_id=job.job_id
where w.prisoner_id=p.prisoner_id and per.person_ssn=p.person_ssn
  1. work表与job
  2. 之间的左连接
  3. workprisoner
  4. 之间的内部联接
  5. personprisoner
  6. 之间的内部联接

答案 5 :(得分:0)

试试这个..

select prisoner_id, first_name, last_name, job_description from prisoner
join person on person.person_ssn = prisoner.person_ssn
left join work on work.prisoner_id = prisoner.prisoner_id
left join job on job.job_id = work.job_id