繁体   English   中英

SQL Query 连接两个类似于左外连接的表

[英]SQL Query joining two tables similar to left outer join

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM