首页 > 解决方案 > 从 col_2 不为空的表中选择 ID(重复 ID)

问题描述

我有一个包含以下数据的表

ID | Col_2
A  | 'ABC'
A  | 'GHI'
A  | null
B  | 'null'
B  | 'HJH'
B  | 'NBN'
C  | null

我有两种情况要处理:

重复 ID:如果出现重复 ID,我只希望那些在 col_2 中没有 null 的 ID 例如查询应该返回:

A  | 'ABC'
A  | 'GHI'
B  | 'HJH'
B  | 'NBN'

非重复 ID:如果 id 不重复,查询应返回结果,而与 col_2 中存在的值无关

所以查询的最终结果应该是

ID | Col_2
A  | 'ABC'
A  | 'GHI'
B  | 'HJH'
B  | 'NBN'
C  | null

我设法创建了以下查询,它满足重复的 id 情况而不是非重复的情况。

询问 :

select id,col_2 
from mytable
group by id,col_2
having (sum(case when col_2 is not null then 1 else 0 end) > 0)

还应在查询中进行哪些更改以适应不重复的情况。

提前致谢!!!

标签: mysqlsql

解决方案


假设NULLisNULL而不是字符串,并且每个 id只有一个NULL值,您可以执行以下操作:

select t.*
from t
where t.col_2 is not null or
      not exists (select 1 from t t2 where t2.id = t.id and t2.col_2 is not null);

如果您的null值可以重复,并且您只需要一行,则将其调整为:

select t.*
from t
where t.col_2 is not null 
union all
select distinct t.*
from t
where not exists (select 1 from t t2 where t2.id = t.id and t2.col_2 is not null);

是一个 db<>fiddle。

出于性能考虑,您需要在(id, col_2).

如果您只想要col_2each 的值id,则可以将它们连接到每一行:

select id, group_concat(col_2)
from t
group by id;

另一种选择使用窗口函数:

select t.id, col_2
from (select t.*,
             rank() over (partition by id order by col_2 is not null desc) as seqnum
      from t
     ) t
where seqnum = 1;

推荐阅读