mysql—获取表的最新版本并按其他表的名称变量排序的sql查询

w1jd8yoj  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(291)

我的sql中有两个表,一个是deployments,另一个是applications。我正在尝试获取最新版本(它是根据update\u at variable计算的),并且我想按应用程序名对它们进行排序。部署表中的应用程序id等于应用程序表中的id。应用程序表中的一行可以包含部署表中的多个部署行,这意味着它们之间存在一对多关系。

Deployment table
id
app_id
version
created_at
updated_at

Application table:
id
name
created_at
updated_at
image

我写了这样的东西,但没用。有人能帮我吗?

SELECT d.*
FROM deployments d
INNER JOIN
(SELECT de.app_id, MAX(de.updated_at) AS MaxDateTime FROM deployments de, applications a GROUP BY de.app_id ORDER BY a.name) grouped_deployments
ON d.app_id = grouped_deployments.app_id
AND d.updated_at = grouped_deployments.MaxDateTime
ubof19bj

ubof19bj1#

如果您只需要每个应用程序的最新版本,一个相关的子查询就足够了:

select 
    a.*,
    (
        select d.version 
        from deployments d 
        where d.app_id = a.id 
        order by d.updated_at desc 
        limit 1
    ) last_version
from applications a
order by a.app_name

这应该是一个有效的解决方案,前提是您在上有一个索引 deployments(app_id, updated_at, version) .
如果您想从 deployments 表,则选项是 join 以及使用相关子查询进行过滤:

select a.app_name, d.version, d.updated_at, d.created_at
from applications a
inner join deployments d on d.app_id = a.id
where d.updated_at = (
    select max(d1.updated_at) from deployments d1 where d1.app_id = a.app_id
)
order by a.app_name
kg7wmglp

kg7wmglp2#

SELECT de.*
FROM application a
INNER JOIN
(SELECT d.app_id, MAX(d.updated_at) AS MaxDateTime FROM deployments d GROUP BY d.app_id) de
on de.app_id = a.id
order by a.name;

为多列编辑:mysql的旧版本允许在选择列表中使用非聚合列。在较新的版本(5.7+)中,可以删除sql模式“only\ full\ group\ by”以获得相同的效果。现在,可以在派生表中添加所有列。
如果需要可移植查询,则需要连接回以获得结果:

SELECT d.*
FROM application a
INNER JOIN
(SELECT d.app_id, MAX(d.updated_at) AS MaxDateTime FROM deployments d GROUP BY d.app_id) de
on de.app_id = a.id
INNER JOIN deployments d
ON d.updated_at = de.update_at
order by a.name;
l5tcr1uw

l5tcr1uw3#

如果您想要每个应用程序的最后一次部署,可以使用 IN 使用聚合子查询:

select * 
from applications a
join deployments d on d.app_id = a.id
where (d.app_id, d.updated_at) in
(
  select app_id, max(updated_at)
  from deployments
  group by app_id
)
order by a.name;

相关问题