我在Oracle数据库中有以下两个表(只读访问权限,所以我只能使用select)。
Question
表:
N Question ID
1 1
2 2
3 3
Response
表:
Question ID Response day
1 01-04-15
3 02-04-15
4 03-04-15
我希望输出结果为:
Question ID Response day
1 01-04-15
2 null
3 02-04-15
4 03-04-15
我正在尝试使用以下查询,并且当有响应时我正在获取问题ID。谁知道我哪里出错?
select questionID, responseday
from questions
join response
where question.question.ID = response.question.ID;
通过此查询,我得到了这些结果:
Question ID Response day
1 01-04-15
3 02-04-15
4 03-04-15
答案 0 :(得分:2)
一种方法是完全外连接:
select coalesce(q.questionid, r.questionid) as questionid,
r.responseday
from questions q full outer join
responses r
on q.questionid = r.questionid;
答案 1 :(得分:0)
使用左连接
delay
答案 2 :(得分:0)
根据您的架构,简单的LEFT JOIN
对您的模型就足够了。
SELECT q.Question_ID,
r.Response_Day
FROM Question AS "q"
LEFT JOIN Response AS "r"
ON r.Question_ID = q.Question_ID;
JOIN
或INNER JOIN
仅会返回ALL属性匹配的两个表中的结果集。由于响应表中不存在ID为Question
的{{1}}记录,因此SQL将排除此数据。
要考虑2
,您必须NULLs
,请在此处查看sqlfiddle:
SQL Fiddle
另外,请看一下解释所有LEFT JOIN
的图形模型:
Visual Representation of SQL Joins
答案 3 :(得分:0)
FULL outer JOIN is sufficient or the output required.
SELECT NVL(a.id,b.id),
b.nm
FROM
(SELECT 1 id,1 nm FROM dual
UNION ALL
SELECT 2 id,2 nm FROM dual
UNION ALL
SELECT 3 id,3 nm FROM dual
)a
FULL OUTER JOIN
(SELECT 1 id,'01-04-15' nm FROM dual
UNION
SELECT 3 id,'02-04-15' nm FROM dual
UNION ALL
SELECT 4 id,'03-04-15' nm FROM dual
)b
ON a.id = b.id;
---------------------------------OUTPUT -----------------------------------
ID NM
1 01-04-15
3 02-04-15
4 03-04-15
2 NULL
----------------------------------OUTPUT-----------------------------------
答案 4 :(得分:-4)
select questionID
, responseday
from questions
join response
on question.question.ID = response.question.ID;