【问题标题】:Get column value if it matches another column value in the same table如果它与同一个表中的另一个列值匹配,则获取列值
【发布时间】:2020-05-18 00:45:15
【问题描述】:

我有一个带有 cmets 的 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?然后是回复 -> get userChannelId where 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】:

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

    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)
    )
    

    请参阅demo
    结果:

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

    【讨论】:

    • 感谢您的回答,但我不得不在运行 30 分钟后终止我的 SQL UI。我的表中有大约 42k 行,也许自联接使它太大了?
    • 我无法在您的实际数据上测试代码,所以我不知道您是否应该期望 42k 行。它适用于您解释的要求以及您发布的示例数据。
    • 我的意思是我的表中有 42k 行。
    • 您的第一个要求:Id == NULL?然后是回复 -> get userChannelId where commentID_parentID == Id 需要自加入,最后一个:Comment "d" has no entry where commentID_parentID == Id 所以它被遗漏了。需要 EXISTS 条件。
    猜你喜欢
    • 2022-08-19
    • 1970-01-01
    • 2022-11-25
    • 2022-01-22
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    相关资源
    最近更新 更多