MySQL GROUP BY,同时按列内容保留某些行
Posted
技术标签:
【中文标题】MySQL GROUP BY,同时按列内容保留某些行【英文标题】:MySQL GROUP BY while keeping certain rows by column content 【发布时间】:2019-11-25 22:09:55 【问题描述】:存在重复行的表。请参阅第 1 行和第 2 行:
id full_name email status active
1 John Doe john@mail.com ok 1
2 John Doe john@mail.com null 1
3 Ricky Duke rick@mail.com null 1
4 Jane Doe jane@mail.com block 1
我需要选择不同的行,而不是随机选择 - 一个不同的行,但要选择具有 'status' NOT NULL 的行。
我的查询是:
SELECT full_name, email
FROM `subscribers`
WHERE active = 1 AND (status = 'ok' OR status IS NULL)
GROUP BY email
该查询随机选择不同的行,而不优先考虑“状态”字段。
我如何优先选择具有 'status' NOT NULL 的不同行,并且仅在不存在“ok”状态的行的情况下才选择具有 NULL 的行? p>
【问题讨论】:
见Why should I provide an MCRE for what seems to me to be a very simple SQL query 【参考方案1】:你可以使用row_number()
:
select s.*
from (select s.*,
row_number() over (partition by email order by (status is not null) desc) as seqnum
from subscribers s
where active = 1
) s
where seqnum = 1;
【讨论】:
【参考方案2】:您可以使用执行条件排序的相关子查询进行过滤,并为null
状态提供最低优先级:
select t.*
from mytable t
where t.id = (
select id
from mytable t1
where
t1.full_name = t.full_name
and t1.email = t.email
and t1.active = t.active
order by status is null, status
limit 1
)
这将重复定义为具有相同 full_name
、email
和 active
的记录。您可能希望根据您对重复项的实际定义进行调整。
Demo on DB Fiddle:
编号 |全名 |电子邮件 |状态 |积极的 -: | :--------- | :------------ | :----- | :----- 1 |约翰·多伊 | john@mail.com |好的 | 1 3 |瑞奇·杜克 | rick@mail.com | 空 | 1 4 |简·多伊 |简@mail.com |块 | 1【讨论】:
【参考方案3】:(SELECT full_name, email
FROM `subscribers`
WHERE active = 1 AND status IS NOT NULL
GROUP BY email)
UNION ALL
(SELECT full_name, email
FROM `subscribers`
WHERE active = 1 AND status IS NULL AND
email not in (SELECT distinct email
FROM `subscribers`
WHERE active = 1 AND status IS NOT NULL)
GROUP BY email);
【讨论】:
以上是关于MySQL GROUP BY,同时按列内容保留某些行的主要内容,如果未能解决你的问题,请参考以下文章
mysql 用 group by 和 order by同时使用