sql - SQL Query 连接两个表,类似于左外连接
问题描述
表1:问题
id | question
----------------
1 | Name
2 | Age
3 | Gender
4 | Position
表2:答案
qid | ans | record
-----------------------
1 | Jay | 1
2 | 24 | 1
3 | M | 1
2 | 23 | 2
我想提出一个连接查询,结果如下表:
record | question | ans
-----------------------------
1 | Name | Jay
1 | Age | 24
1 | Gender | M
1 | Position | null
2 | Name | null
2 | Age | 23
2 | Gender | null
2 | Position | null
我能想到的最接近的是这个加入:
select a.record, q.question, a.ans
from
question q left outer join answer a
on q.id = a.qid order by a.record,q.id;
然而,这个查询只产生这个,但我希望所有的问题都显示两次
record | question | ans
-----------------------------
1 | Name | Jay
1 | Age | 24
1 | Gender | M
1 | Position | null
2 | Age | 23
解决方案
您需要一个交叉连接来生成您需要的所有组合,并与左连接配对以检索答案,如下所示:
select
r.record,
q.question,
a.ans
from question q
cross join (select distinct record from answer) r
left join answer a on a.record = r.record and a.qid = q.id
order by r.record, q.id
结果:
record question ans
------ -------- ------
1 Name Jay
1 Age 24
1 Gender M
1 Position <null>
2 Name <null>
2 Age 23
2 Gender <null>
2 Position <null>
作为参考,这是我用来验证案例的测试脚本:
create table question (
id int,
question varchar(10)
);
insert into question (id, question) values
(1, 'Name'),
(2, 'Age'),
(3, 'Gender'),
(4, 'Position');
create table answer (
qid int,
ans varchar(10),
record int
);
insert into answer (qid, ans, record) values
(1, 'Jay', 1),
(2, '24', 1),
(3, 'M', 1),
(2, '23', 2);
推荐阅读
- php - Laravel - 路由资源更新功能不起作用
- java - 如何通过 applicationinsights-agent 将多个应用程序洞察与一个 Java Web 应用程序联系起来?
- python - 如何制作具有可训练权重和可定义输入数量的加权和层?
- c++ - `istream` 到浮点数组(每个项目 4 字节)
- android - 如何使用为 Android 12 发布的新 Material You 颜色
- python - Pyinstaller 在终端停止并且不会继续
- azure-data-explorer - LightIngest 未摄取,停留在发布摄取:0
- python - 如何匹配特定单词之前没有的字符串?
- javascript - 打破承诺链
- javascript - 无法访问赛普拉斯中的模态对话