SQL - Select 具有小于集合修订的最大修订的行
SQL - Select rows with greatest revision that are less than a set revision
我有一个审计 table,其中实体按 ID 和相关的修订号和修订类型存储(这是一个 Hibernate Envers 审计 table)。
例如
id
rev
revtype
foo_description
10
1
0
10 foo v1
10
3
1
10 foo v2
10
4
1
10 foo v3
20
2
0
20 foo v1
20
4
1
20 foo v2
我如何查询这个 table 以便我得到每个 id 的最新版本小于指定的版本,例如版本=4?
从上面的例子table来看,最新版本小于rev=4的查询结果应该是:
id
rev
revtype
foo_description
10
3
1
10 foo v2
20
2
0
20 foo v1
我正在使用 MySQL 数据库,版本 5.7。
在 mysql 8+:
select * from (
select * , row_number() over (partition by id order by rev desc) rn
from tablename
where rev < 4
) t where rn = 1
在 mysql 5.7:
select * from mytable t1
where (id,rev) = (
select id, rev from mytable t2
where t2.rev < 4
and t1.id = t2.id
order by rev desc limit 1
)
db<>fiddle here
我有一个审计 table,其中实体按 ID 和相关的修订号和修订类型存储(这是一个 Hibernate Envers 审计 table)。
例如
id | rev | revtype | foo_description |
---|---|---|---|
10 | 1 | 0 | 10 foo v1 |
10 | 3 | 1 | 10 foo v2 |
10 | 4 | 1 | 10 foo v3 |
20 | 2 | 0 | 20 foo v1 |
20 | 4 | 1 | 20 foo v2 |
我如何查询这个 table 以便我得到每个 id 的最新版本小于指定的版本,例如版本=4?
从上面的例子table来看,最新版本小于rev=4的查询结果应该是:
id | rev | revtype | foo_description |
---|---|---|---|
10 | 3 | 1 | 10 foo v2 |
20 | 2 | 0 | 20 foo v1 |
我正在使用 MySQL 数据库,版本 5.7。
在 mysql 8+:
select * from (
select * , row_number() over (partition by id order by rev desc) rn
from tablename
where rev < 4
) t where rn = 1
在 mysql 5.7:
select * from mytable t1
where (id,rev) = (
select id, rev from mytable t2
where t2.rev < 4
and t1.id = t2.id
order by rev desc limit 1
)
db<>fiddle here