繁体   English   中英

如何根据条件在两个表之间建立连接,以保留每个表中的特定记录

[英]How can I make a join between two tables keeping specific records from each table according to a condition

我有两个表 t1, t2 例如,我想从 t1 获取所有结果,除非 itemType = '01' 在这种情况下,我想保留来自 t2 的对应 itemType='01' 记录,这是我唯一的记录想从t2。

尝试对该字段的 case 语句这种方式仅根据您描述的条件选择该字段

假设在下面的示例中是内连接,但是我们可以将其更改为外连接并添加一些处理空值的逻辑。

根据数据中的关系,您可能需要分组以获取正确的信息级别/避免重复。 仍然这个例子应该有帮助

例如,

select t1.field1, t1.field2, etc, 

case 
when t1.itemType = '01' then t2.itemType 
else t1.itemType 
end 

from
(
  (select * from tableA) as T1
    inner join
  (select * from tableB) as T2
     On T1.key1 = T2.key1
)

我怀疑你想要UNION ALL而不是JOIN

select * from t1
where itemtype <> '01'
union all
select * from t2
where itemtype = '01'

我认为带有过滤的left join会解析为您给出的描述:

select t1.*, t2.*
from t1 join
     t2
     on t2.? = t1.? and  -- however you define corresponding
        t2.itemType = '01'
where t1.itemType <> '01';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM