Sql 将外键旋转到行

Sql 将外键旋转到行,sql,Sql,我有两个表需要连接在一起,但是我不希望它们只是更多的相同记录,而是希望它们返回一个“标记”列作为行 我有这样的设置: create table main_record( id int not null primary key, foo_entry_id int not null, bar_entry_id int not null ); create table entry ( id int not null primary key, entry_value varchar

我有两个表需要连接在一起,但是我不希望它们只是更多的相同记录,而是希望它们返回一个“标记”列作为行

我有这样的设置:

create table main_record(
  id int not null primary key,
  foo_entry_id int not null,
  bar_entry_id int not null
);

create table entry (
  id int not null primary key,
  entry_value varchar(255) not null
);

insert into entry values (1, 'foo');
insert into entry values (2, 'bar');

insert into main_record values (1, 1, 2);

select
    case when e1.id is null then 'should be foo'
    else 'should be bar' end as a_label,
    e1.id as foo_id,
    e2.id as bar_id
from main_record mr
left join entry e1 on mr.foo_entry_id = e1.id
left join entry e2 on mr.bar_entry_id = e2.id;
我只拿回一张唱片:

+ ------------- + ----------- + ----------- +
| a_label       | foo_id      | bar_id      |
+ ------------- + ----------- + ----------- +
| should be bar | 1           | 2           |
+ ------------- + ----------- + ----------- +
我需要这样的东西:

+ ------------- + ----------- + ----------- +
| a_label       | foo_id      | bar_id      |
+ ------------- + ----------- + ----------- +
| should be foo | 1           | NULL        |
+ ------------- + ----------- + ----------- +
| should be bar | NULL        | 2           |
+ ------------- + ----------- + ----------- +
编辑
我目前正在使用一个
UNION
来实现这一点,但是为了文章的长度,我忽略了其余部分。我正试图避免使用
联合
,因此我可以只对较大查询的一部分执行此操作。

分别执行两个
联合
,并将结果与
联合

select
   'should be foo'  a_label,
     e.id  foo_id,
     null  bar_id
from main_record mr
left join entry e
on mr.foo_entry_id = e.id
union
select
   'should be bar',
     null, 
     e.id   
from main_record mr
left join entry e
on mr.bar_entry_id = e.id

为了安全起见,我会做
UNION-ALL
,我必须用更大的查询做4次,我希望避免
UNION
(实际上我现在使用的是
UNION
)。我应该在OP中提到这一点,我现在正在更新它。