且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取列值(如果它与同一表中的另一个列值匹配)

更新时间:2022-12-12 10:46:42

这是一个相当复杂的要求,但我认为有条件的自我连接可以做到:

It's a rather complicated requirement but I think that a conditional self join will do it:

select t.usernameChannelId userChannelId_Source, 
  case 
    when t.id is not null then tt.channelId
    else tt.usernameChannelId 
  end userChannelId_Target 
from tablename t inner join tablename tt
on tt.id = coalesce(t.id, t.commentID_parentID)
and exists (
  select 1 from tablename 
  where commentID_parentID = t.id
  or (commentID_parentID is null and t.id is null)
)

请参见演示

结果:

See the demo.
Results:

| userChannelId_Source | userChannelId_Target |
| -------------------- | -------------------- |
| a                    | g                    |
| a                    | a                    |
| c                    | a                    |
| b                    | k                    |
| g                    | b                    |