如果右侧表没有数据,则联接表以显示空

问题描述

我有一个feedback_ques,feedback_ans表,如下所示:

feedback_ques
 
id  question                created_date    created_by delete_date
1   How was the training    16-SEP-20       900         null
2   facility?               16-SEP-20       900         null    
3   Dept?                   16-SEP-20       902         null
4   Infrastructure          16-SEP-20       900         16-SEP-20

feedback_ans

ques_id member_id   answers created_date    created_by
1       10          good    16-SEP-20       891
2       10          good    16-SEP-20       891
3       10          poor    16-SEP-20       891
4       10          good    16-SEP-20       891

我要按如下方式加入表:

select q.id as id,a.member_id as memberId,q.question as Ques,a.answers as Ans
from feedback_ques q,feedback_ans a
where q.id = a.ques_id(+) 
and a.member_id = 10
and q.DELETE_DATE IS NULL;

这给了我所有领域。如果查询表中未找到答案,我希望查询返回null。 例如member_id 20没有答案,因此我希望该表在此查询中显示如下的空值。

select q.id as id,feedback_ans a
where q.id = a.ques_id(+) 
and a.member_id = 20
and q.DELETE_DATE IS NULL;

ID  memberId    Ques                    ans
1   20          How was the training    null
2   20          facility?               null
3   20          Dept?                   null
4   20          Infrastructure          null

已更新: 如我所建议的那样,使用leftOuter连接如下:

select q.id as id,a.answers as Ans
from feedback_ques q
left join feedback_ans a on a.ques_id = q.id and a.member_id = 20
and q.delete_date is null;

但是,当delete_date为!= null时,此查询不起作用。该行仍由查询返回。由于delete_date!= null,因此不应返回上述任务4。 你能帮忙吗?

解决方法

这些老式的隐式联接使表达您想要的内容变得不容易。这里,where子句中的条件a.member_id = 20过滤掉不匹配的行。

这只是应始终使用显式标准联接的原因之一。考虑一个left join,其中左表上的所有条件都放在on子句中:

select q.id as id,a.member_id as memberId,q.question as Ques,a.answers as Ans
from feedback_ques q
left join feedback_ans a on a.ques_id = q.id and a.member_id = 20
where q.delete_date is null;

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...