[英]Join tables to display null if right side table doesnt have data
我有一個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, 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 = 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 join 如下:
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
and q.delete_date is null;
但是當 delete_date 為 !=null 時,此查詢不起作用。 該行仍由查詢返回。 從上面的任務 4 不應該返回,因為 delete_date != null。 你能幫忙嗎。
這些陳舊的、隱式的連接讓你很難表達你想要的東西。 這里,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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.