一个表中缺少ID,无论如何都将其包含在结果中

时间:2018-04-18 21:41:48

标签: mysql sql

在我的mySQL数据库中,我有两个名为job_details和job_actions的表。在job_details表中,如果我获得了Job_ID 41230的Detail_ID,那么我得到五个结果。例如:

select Detail_ID from job_details where Job_ID = '41230';

enter image description here

我想要做的是使用相同的Job_ID从job_actions表中获取每个Detail_ID的Percent_Complete。例如,这只会产生4条记录,因为并非所有Detail_ID都显示在此表中:

select Detail_ID, Percent_Complete from job_actions where Job_ID = '41230';

enter image description here

当我尝试加入两个表时,我得到相同的四条记录:

select 
    details.Detail_ID,
    actions.Percent_Complete
from 
    job_details details,
    job_actions actions
where 
    details.Job_ID = '41230' and
    details.Job_ID = actions.Job_ID and
    details.Detail_ID = actions.Detail_ID;

我希望我的输出包含在job_details表中找到的每个Detail_ID,即使在job_actions表中找不到它。例如:

enter image description here

我知道如何找到job_actions表中缺少的Detail_ID,但不知道如何在结果中包含它。例如:

select details.Detail_ID from job_details details 
left join job_actions actions using (Detail_ID) 
where actions.Detail_ID IS NULL and details.Job_ID = '41230';

如果在job_actions表中缺少Detail_ID 87679,我怎么能在结果中包含它?

2 个答案:

答案 0 :(得分:1)

从不FROM子句中使用逗号。 始终使用正确,明确,标准的JOIN语法。

您只需要一个LEFT JOIN

select details.Detail_ID, actions.Percent_Complete
from job_details details left join
     job_actions actions
     on details.Job_ID = actions.Job_ID and
        details.Detail_ID = actions.Detail_ID
where details.Job_ID = 41230;  -- I assume Job_ID is a number so the single quotes are not necessary

答案 1 :(得分:1)

因为,您已经编写了joins的语法,但使用旧样式的 where 子句可以变为实际的内部连接或 equi < / em>加入。

因此,请使用类型为join

的正确显式left join语法
select jd.Detail_ID, ja.Percent_Complete 
from job_details jd left join job_actions ja on 
                    ja.Job_ID = jd.Job_ID and
                    ja.Detail_ID = jd.Detail_ID 
where jd.Job_ID = '41230';

您也可以使用subquery,因为您正在寻找Detail_ID表中的所有job_details

select Detail_ID,
       (select Percent_Complete from job_actions 
        where Job_ID = jd.Job_ID and 
              Detail_ID = jd.Detail_ID) as Percent_Complete  -- Use limit  with order by clause in case one or more Percent found. 
from job_details jd 
where Job_ID = '41230';

我怀疑,如果您有Job_ID作为数字的类型,那么您不需要使用引号只需使用(即 41230