首页 > 解决方案 > 在 SQL 中连接两个表

问题描述

表1:

CID   Detail
1     d1
2     d2
3     d3

表2:

ID     CID    FileType
1      1      1
2      1      2
3      2      2

所需结果:全部来自 Table1,如果 FileType 为 null 或 <> 1,则为 null

CID   Detail  FileType
1     d1      1
2     d2      null
3     d3      null

标签: sql

解决方案


我认为您正在寻找 1-1 分配。像这样的东西:

select t1.*, t2.FileType
from tbl1 t1 left join
     (select tbl2.*,
             row_number() over (partition by cid order by id) as seqnum
      from tbl2
     ) t2
     on t2.cid = t1.cid and t2.seqnum = 1 and
        t2.FileType = 1;

推荐阅读