Sql 表3优于表2,表2优于表1

Sql 表3优于表2,表2优于表1,sql,Sql,我有3张桌子,上面有我几个朋友的名字和号码 表3有正确的数据,表2有微小的数据错误,表1有多于表2的数据错误 如果表2和表3中存在用户,则在output else表2 details中显示表3的详细信息;如果表2中甚至没有用户,则显示表1中的用户数据 更像是优先顺序 虚拟数据: table 1 : name phone abc 2343 bcd 3434 ccd 3455 ffc 4545 table 2 : name phone abc 2313 bcd 3414

我有3张桌子,上面有我几个朋友的名字和号码

表3有正确的数据,表2有微小的数据错误,表1有多于表2的数据错误

如果表2和表3中存在用户,则在output else表2 details中显示表3的详细信息;如果表2中甚至没有用户,则显示表1中的用户数据

更像是优先顺序

虚拟数据:

table 1 :

name phone
abc   2343
bcd   3434
ccd   3455
ffc   4545

table 2 :

name phone
abc   2313
bcd   3414
ccd   3415


table 3 :

name phone
abc   2344
bcd   3431
预期产出:

name phone
abc   2344
bcd   3431
ccd   3415
ffc   4545
我尝试了此查询,但找不到正确的输出

select phone,
    coalesce(table1.name, TABLE2.name,TABLE3.name) as namee
FROM   TABLE1
       left JOIN TABLE2 
               ON table1.name = table2.name
       INNER JOIN table3
               ON table3.name = table2.name

将是一个巨大的Heeelpppp。

使用
union all

select t1.*
from table1 t1
union all
select t2.*
from table2 t2
where not exists (select 1 from table1 t1 where t1.name = t2.name)
union all
select t3.*
from table3 t3
where not exists (select 1 from table1 t1 where t1.name = t3.name) and
      not exists (select 1 from table2 t2 where t2.name = t3.name);
  

戈登很接近;他有相反的偏好。请确保您理解脚本工作的原因

-- grab all our preferred data first
select t3.*
from table3 t3

union all

-- grab anything that doesn't exist in our preferred table
select t2.*
from table2 t2
where not exists (select 1 from table3 t3 where t3.name = t2.name)

union all

-- grab anything that doesn't exist in our preferred tables
select t1.*
from table1 t1
where not exists (select 1 from table2 t2 where t2.name = t1.name) and
      not exists (select 1 from table3 t3 where t3.name = t1.name);

给出错误的输出,我从表1而不是表3得到“abc”,从表2而不是表3得到“bcd”3@yono . . . 如果您的顺序是表1-->表3-->表2,则只需交换表名即可。