Sql 如果存在,请从另一个表中选择列
我需要帮助解决这个问题。我有两张桌子: 表1Sql 如果存在,请从另一个表中选择列,sql,Sql,我需要帮助解决这个问题。我有两张桌子: 表1 MonthYear Code Value jan/18 4169 50 jan/18 4102 95 表2 Date Code Value jan/18 4102 30 jan/18 4102 10 jan/18 4102 15 jan/18 4102 40 我需要做一个查询,如果表2中没有代码,则返回表1的值字段;如果表2中有代码,则返回表2的值字段 例如:
MonthYear Code Value
jan/18 4169 50
jan/18 4102 95
表2
Date Code Value
jan/18 4102 30
jan/18 4102 10
jan/18 4102 15
jan/18 4102 40
我需要做一个查询,如果表2中没有代码,则返回表1的值字段;如果表2中有代码,则返回表2的值字段
例如:
MonthYear Code Value
jan/18 4169 50
jan/18 4102 30
jan/18 4102 10
jan/18 4102 15
jan/18 4102 40
我的做法如下:
select t2.date, t2.code, t2.value
from table2 t2
union all
select t1.date, t1.code, t1.value
from table2 t1
where not exists (select 1 from table2 t2 where t1.date = t2.date and t1.code = t2.code);
我的做法如下:
select t2.date, t2.code, t2.value
from table2 t2
union all
select t1.date, t1.code, t1.value
from table2 t1
where not exists (select 1 from table2 t2 where t1.date = t2.date and t1.code = t2.code);
您可以使用
合并:
select t1.MonthYear,
coalesce(t2.Code,t1.Code) as Code,
coalesce(t2.value,t1.value) as value
from table2 t2
right outer join table1 t1
on ( t2.Code = t1.Code );
另外,我选择了PostGreSQL作为演示数据库,您也可以将此SQL用于Oracle、SQL Server或MySQL
实际上,您最好将SQL中的关键字right
替换为full
,如下所示:
select coalesce(t2.MonthYear,t1.MonthYear) as MonthYear,
coalesce(t2.Code,t1.Code) as Code,
coalesce(t2.value,t1.value) as value
from table2 t2
full outer join table1 t1
on ( t2.Code = t1.Code );
除了MySQL,由于出现了另一种情况,代码存在于表2中,而不是表1中,完全外部连接提供了解决方案(特别感谢@Error_2646)。您可以使用合并
:
select t1.MonthYear,
coalesce(t2.Code,t1.Code) as Code,
coalesce(t2.value,t1.value) as value
from table2 t2
right outer join table1 t1
on ( t2.Code = t1.Code );
另外,我选择了PostGreSQL作为演示数据库,您也可以将此SQL用于Oracle、SQL Server或MySQL
实际上,您最好将SQL中的关键字right
替换为full
,如下所示:
select coalesce(t2.MonthYear,t1.MonthYear) as MonthYear,
coalesce(t2.Code,t1.Code) as Code,
coalesce(t2.value,t1.value) as value
from table2 t2
full outer join table1 t1
on ( t2.Code = t1.Code );
除了MySQL之外,由于出现了另一种情况,代码存在于表2中,而不是表1,完全外部连接提供了解决方案(特别感谢@Error_2646).请用您正在使用的数据库标记您的问题。请用您正在使用的数据库标记您的问题。如果表2中存在代码,但表1中不存在代码-这不会删除这些记录吗?@Error\u 2646我们可以将right
替换为full
fororacle
或postgreSQL
或SQL Server
,但是对于这个问题没有数据库限制,对于这个数据集,此SQL满足所需的结果。如果代码存在于表2中,而不是表1中,该怎么办?这不会删除这些记录吗?@Error\u 2646我们可以通过将right
替换为full
来管理它,以便oracle
或postgreSQL
或SQL Server
,但是对于这个问题,没有数据库限制,对于这个数据集,这个SQL满足期望的结果。