如果与同一表中的另一个列值匹配,则获取列值

问题描述 投票:0回答:1

我有一个带有注释的SQLite表:

Id   | replyId | commentID_parentID | usernameChannelId | channelId
1    | NULL    | NULL               | a                 | g
2    | NULL    | NULL               | b                 | k
NULL | 1.k     | 1                  | a                 | p
NULL | 1.p     | 1                  | c                 | i
3    | NULL    | NULL               | d                 | h
NULL | 2.k     | 2                  | g                 | g

和带有如下频道的表:

我想知道哪个用户(userChannelId)回复了哪个用户。

所以我在一行中加上评论,然后检查是否:

  • Id == NULL?然后是一个回复->获取userChannelId,其中commentID_parentID == ID
  • Id!= NULL?然后是主要注释-> userChannelId回复为channelId

结果应该是:

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

注释“ d”没有其中commentID_parentID == ID的条目,因此被忽略了。

在同一张表中查询时如何在SQL中执行此操作?

sql sqlite conditional-statements
1个回答
0
投票

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

select t.userChannelId userChannelId_Source, 
  case 
    when t.id is not null then tt.channelId
    else tt.userChannelId 
  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)

请参见demo。结果:

| userChannelId_Source | userChannelId_Target |
| -------------------- | -------------------- |
| a                    | g                    |
| a                    | a                    |
| c                    | a                    |
| b                    | k                    |
| g                    | b                    |
© www.soinside.com 2019 - 2024. All rights reserved.