Get column value if it matches another column value in the same table

半腔热情 提交于 2020-03-05 06:05:16

问题


I have a SQLite table with comments like:

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

and a table with channels like:

I want to know which user (userChannelId) replied to which user.

So I take a row with a comment and check if:

  • Id == NULL? Then it's a reply -> get userChannelId where commentID_parentID == Id
  • Id != NULL? Then it's a main comment -> userChannelId replied to channelId

And result should be:

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

Comment "d" has no entry where commentID_parentID == Id so it's left out.

How can I do that in SQL when I query in the same table?


回答1:


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                    |


来源:https://stackoverflow.com/questions/60019276/get-column-value-if-it-matches-another-column-value-in-the-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!