gpt4 book ai didi

SQL查询连接两个表类似于左外连接

转载 作者:行者123 更新时间:2023-11-29 12:07:11 25 4
gpt4 key购买 nike

表 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);

关于SQL查询连接两个表类似于左外连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57226068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com