从一个表中选择一行,如果不存在,从另一个表中选择

Jim*_*mmy 2 postgresql select postgresql-9.6

如何从一个表中选择一行,但如果它不存在,则回退到从辅助表中选择它?这是我想要实现的简化版本

create table table_1 (
  person TEXT,
  favourite_number INT
  );
  
  create table table_2 (
    person TEXT,
    favourite_number INT
  );
  
  insert into table_1 (person, favourite_number) values 
  ('Bob', 1),
  ('Fred', 2)
  ;
  
    insert into table_2 (person, favourite_number) values 
  ('Bob', 30),
  ('Alice', 70)
  ;
Run Code Online (Sandbox Code Playgroud)

我想得到以下结果:

| person | favourite_number |
|--------|------------------|
| Bob    | 1                |
| Alice  | 70               |
| Fred   | 2                |
Run Code Online (Sandbox Code Playgroud)

注意它如何从第一个表中选择 Bob 和 Fred。即使鲍勃出现在第二张桌子上,因为我们已经拿到了他,我们还是把他从第一张桌子上拿走了。Alice 只出现在第二个表中。

到目前为止,这是我尝试过的,但我无法让所有 3 个返回,请帮助。

select
  t1.*
from table_1 t1
where t1.person not in (select person from table_2)
union
select
  t2.*
from table_2 t2
where t2.person not in (select person from table_1)
;
Run Code Online (Sandbox Code Playgroud)

And*_*yer 6

如果更可取的是从第一个表中选择行,您应该去掉当其他人存在时将删除它们的过滤器。

也不需要区分行,所以使用union all代替union

select
  t1.*
from table_1 t1
union all
select
  t2.*
from table_2 t2
where t2.person not in (select person from table_1)
Run Code Online (Sandbox Code Playgroud)