mysql查询根据多个条件连接4个表

时间:2012-11-20 15:09:40

标签: mysql join

我在mysql中有四个表,如下所示:

enter image description here

enter image description here

我想要做的是一起加入表格,以显示是否已经为部门中的每个用户进行了培训,如果已经完成,则显示培训日期,否则说需要培训。

所以部门财务的期望输出将是:

enter image description here

我已尝试使用以下代码,但联接变得不准确且无效。

select o.person, o.job, j.risk, r. training,c.course,
    c.person,c.datecompleted 
from orgstructure o 
left outer join jobsrisks j 
    on o.job=j.job 
left outer join risktraining r 
    on j.risk=r.risk 
left outer join coursescompleted c 
    on o.person=c.person 
where o.department='finance'

我应该将多个选择查询嵌入到一个中吗?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:15)

我猜这个问题是您只是orgstructure加入coursescompletedperson,我认为您还需要加入培训:

select o.person, 
  o.job, 
  j.risk, 
  r.training,
  c.course,
  c.person,
  c.datecompleted 
from orgstructure o 
left outer join jobsrisks j 
  on o.job=j.job 
left outer join risktraining r 
  on j.risk=r.risk 
left outer join coursescompleted c 
  on o.person=c.person 
  and r.training = c.course   --- add this
where o.department='finance'

如果该人已完成与该工作相关的每项风险的课程,您需要加入此人。

将整个查询放在一起,您将拥有:

select o.person, 
  o.job, 
  j.risk, 
  r.training,
  case when c.course is null then 'no' else 'yes' end TrainingCompleted,
  coalesce(c.datecompleted, 'n/a') datecompleted
from orgstructure o 
left outer join jobsrisks j 
  on o.job=j.job 
left outer join risktraining r 
  on j.risk=r.risk 
left outer join coursescompleted c 
  on o.person=c.person 
  and r.training = c.course   
where o.department='finance'

请参阅SQL Fiddle with Demo

结果是:

|        PERSON |        JOB |                     RISK |                  TRAINING | TRAININGCOMPLETED |       DATECOMPLETED |
-------------------------------------------------------------------------------------------------------------------------------
| taylor chetty |    manager |                   safety |          induction course |                no |                 n/a |
| taylor chetty |    manager |                 security |           security course |                no |                 n/a |
| bill thompson | data clerk |              bad posture | personal wellbeing course |                no |                 n/a |
| bill thompson | data clerk | repetitive strain injury |            nursing course |               yes | 2000-04-13 00:00:00 |
| bill thompson | data clerk |                   safety |          induction course |               yes | 2007-12-04 00:00:00 |
|     ann brown | data clerk |              bad posture | personal wellbeing course |                no |                 n/a |
|     ann brown | data clerk | repetitive strain injury |            nursing course |                no |                 n/a |
|     ann brown | data clerk |                   safety |          induction course |                no |                 n/a |