首页 > 解决方案 > 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

标签: sqlpostgresqljoin

解决方案


您需要一个交叉连接来生成您需要的所有组合,并与左连接配对以检索答案,如下所示:

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

推荐阅读