【问题标题】:SQL Ignore null value if a row with the same ID existsSQL 如果存在具有相同 ID 的行,则忽略空值
【发布时间】:2013-02-06 16:58:45
【问题描述】:

我有一个包含以下数据的 Sybase 表(示例):

Users:

 ID        Type         PlayerID
 --------  -----------  ------------------- 
 65823     1            (null)              
 65823     2            187                 
 91817     1            (null)                         
 37950     1            773                 
 37950     1            (null)              
 37968     1            (null)              
 37968     1            773                                
 72576     1            (null)              
 72576     1            (null)                

我想返回用户和类型的所有组合,但如果特定用户/类型组合的多个示例仅显示不为空的记录强>。

例如上表应返回以下内容

 ID        Type         PlayerID
 --------  -----------  ------------------- 
 65823     1            (null)           - although this is null the type/id is unique   
 65823     2            187              
 91817     1            (null)           - this is null but is a unique type/id              
 37950     1            773                                         
 37968     1            773              - this is included and the id/type that has a null player id isn't                              
 72576     1            (null)           - this is a unique type/id

到目前为止,我已经研究了使用 group by、have 和 inner joins 的查询,但无法找到一种方法来匹配我正在寻找的结果。

我还研究了分组依据,然后在 PlayerID 上使用 max,但聚合函数会忽略空值。

如何返回唯一的 ID/类型对及其玩家 ID?

--

来自保罗的问题:

ID        Type         PlayerID
 --------  -----------  ------------------- 
 65823     2            187                        
 37950     1            773                                         
 37968     1            773    

【问题讨论】:

  • 您能否包含产生最佳结果的初始查询?
  • 嗨,马特,这只是 SELECT * FROM users,在我的示例中,我删除了实际在表中的不相关列。

标签: sql sybase


【解决方案1】:

从 SQL 端你可以这样做:

select * from mytable t1 where playerId is not null
union
select * from mytable t2 where playerid is null 
   and not exists (
          select * from mytable t3 where t2.id=t2.id and t2.type=t3.type
       )

我不知道它会有多有效,但它会给你你想要的结果。

【讨论】:

  • 这行得通,正如您指出的那样,它很慢,但可以完成工作。也许我会研究这种逻辑在应用程序端的可能性。
  • 如果需要频繁运行,尝试优化not exists子句。
【解决方案2】:

是什么

select  ID, type, max(PlayerID)
from    Users
group by ID, type

返回? (我没用过sybase)

【讨论】:

  • 它会忽略空值(max 会),所以您只会看到类似于我刚刚添加的信息的内容。实际上与 PlayerID 列上的 != null 相同
  • 这是一个答案吗?您应该将其更改为评论。
猜你喜欢
  • 2022-10-08
  • 1970-01-01
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
相关资源
最近更新 更多