mysql - 从 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)
还应在查询中进行哪些更改以适应不重复的情况。
提前致谢!!!
解决方案
假设NULL
isNULL
而不是字符串,并且每个 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_2
each 的值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;
推荐阅读
- java - 尝试为对象分配随机 ID
- html - 打开软件键盘时保持页脚可见
- android - 具有多个主题的firebase消息传递条件不起作用
- javascript - 如何在不先单击的情况下自动注销用户会话
- tableau-api - Tableau 中的条件格式连接到多维数据集数据
- apache - 如何为多个域变体生成 LetsEncrypt 证书?
- javascript - 如何使用 OfficeJS 获取带有 Outlook 365 消息打印预览的 URL?
- java - 使用 ButterKnife 处理自定义 AlertDialog 时出现异常
- java - Android 中的电话目录以及从其中获取任何内容的问题
- python - 将产量输出传递给工作人员池时出现 Python 类型错误。想把一个大文件分成几行