mysql - MySQL - 在某些列上运行不同的命令
问题描述
我正在尝试在以下查询中的四列上运行不同的:
select
full_records.id,
full_records.domain_id,
subdomains.name as subdomain_name,
types.name as type_name,
changelog.content as content,
changelog.changed_on
from full_records
inner join subdomains on full_records.subdomain_id = subdomains.id
inner join types on full_records.type_id = types.id
inner join changelog on full_records.id = changelog.full_record_id
where
full_records.domain_id = 2
order by changelog.changed_on desc
这将返回以下内容:
我不确定如何更改查询,以便它只返回这四个字段中唯一的记录。
full_records.domain_id,
subdomains.name as subdomain_name,
types.name as type_name,
changelog.content as content
因此,如果它们在这四个字段中是唯一的,那么第 2、3、4 和 7 行将不会出现在结果中。它基本上是为了识别域记录的最新更改。任何帮助将非常感激。谢谢。
解决方案
一种非常简单的方法是row_number()
:
with cte as (
select fr.id, fr.domain_id, sd.name as subdomain_name,
t.name as type_name, cl.content, cl.changed_on
from full_records fr join
subdomains sd
on fr.subdomain_id = sd.id join
types t
on fr.type_id = t.id join
changelog cl
on fr.id = cl.full_record_id
where fr.domain_id = 2
)
select cte.*
from (select cte.*,
row_number() over (partition by domain_id, subdomain_name, type_name, content
order by changed_on desc
) as seqnum
from cte
) cte
where seqnum = 1;
请注意,我添加了表别名,因此查询更易于编写和阅读。
推荐阅读
- java - 从 JSP 文件调用 Java 方法
- c++ - 迭代器会导致内存泄漏吗?
- powershell - Cosmos DB Rest API - 创建用户权限
- c# - 如何在 Mac 上的 Visual Studio 中编译 C# 应用程序?
- excel - 使用插入重新排序列 VBA 时出现“此选择无效”错误
- angular - 选择更改后让 MatSelect 保持打开状态
- laravel - 使用 Vuejs 从我的选择表单中获取双精度值
- r - 如何用 AND 或 OR 折叠逻辑向量?
- mysql - SQL:如何找到支付 80% 收入的顶级客户?
- python - 对文本类型的特征进行向量化后,机器学习算法不起作用