两表加法

时间:2015-06-10 20:56:32

标签: sqlite

 `ForgeRock Table`

id      status  rank    Name            description
---------------------------------------------------------
1        0      111      jax              music
2        0      234      kevin              art 
3        0      456      DJ              music

 `ForgeRock1 Table`

id      status  rank    Name            description
---------------------------------------------------------
1        1      111      jax              swim
2        1      234      kevin             tennis 
4        0      456      Devil             football

预期结果

id      status  rank    Name            description
---------------------------------------------------------
1        1      111      jax               swim
2        1      234      kevin             tennis 
3        0      456      DJ                music
4        0      456      Devil             football

如果状态字段更改为1,则接受与status = 1相对应的记录并保留所有记录。

查询:

 Select * from ForgeRock
     Union
 Select * from ForgeRock1

1 个答案:

答案 0 :(得分:1)

您可以使用Inner JOINUNION尝试这样做。下面的查询执行Inner join,因此只有匹配的记录(1,2)出现,并根据状态值b / w我们决定使用CASE语句选择哪个值的表。您可以在JOINS/CASE expression文档中详细了解SqlLite

 Select f1.id,
      case when f1.status = 1 then f1.status else f2.status end as Status,
      f1.rank,
      f1.Name,
      case when f1.status = 1 then f1.description else f2.description end as description
      from ForgeRock f1
 inner join ForgeRock1 f2 on f1.id = f2.id 

     union all

 Select id,
      Status,
      rank,
      Name,
      description 
      from ForgeRock
   where id not in (select distinct id from ForgeRock1)

union all

 Select id,
      Status,
      rank,
      Name,
      description 
      from ForgeRock1
   where id not in (select distinct id from ForgeRock)