I have the following table documents
+--------+-------------+------------+----------+---------+
| doc_id | module_name | mapping_id | doc_type | version |
+--------+-------------+------------+----------+---------+
| 5 | asdf | asd | POI | 1 |
| 6 | asdf | asd | POI | 2 |
| 7 | asdf | asd | CAF | 1 |
| 8 | asdf | abc | POI | 1 |
| 9 | asdf | abc | ISR | 1 |
| 10 | asdf | abc | ISR | 2 |
| 11 | asdf | xyz | POA | 1 |
| 12 | asdf | xyz | CAF | 1 |
| 13 | asdf | xyz | CAF | 2 |
| 14 | asdf | xyz | CAF | 3 |
| 15 | pqrs | asd | POI | 1 |
| 16 | pqrs | asd | POI | 2 |
| 17 | pqrs | asd | CAF | 1 |
| 18 | pqrs | abc | POI | 1 |
| 19 | pqrs | abc | ISR | 1 |
| 20 | pqrs | abc | ISR | 2 |
| 21 | pqrs | xyz | POA | 1 |
| 22 | pqrs | xyz | CAF | 1 |
| 23 | pqrs | xyz | CAF | 2 |
| 24 | pqrs | xyz | CAF | 3 |
+--------+-------------+------------+----------+---------+
and I want to get results as:
+--------+-------------+------------+----------+---------+
| doc_id | module_name | mapping_id | doc_type | version |
+--------+-------------+------------+----------+---------+
| 6 | asdf | asd | POI | 2 |
| 7 | asdf | asd | CAF | 1 |
| 8 | asdf | abc | POI | 1 |
| 10 | asdf | abc | ISR | 2 |
| 11 | asdf | xyz | POA | 1 |
| 14 | asdf | xyz | CAF | 3 |
| 16 | pqrs | asd | POI | 2 |
| 17 | pqrs | asd | CAF | 1 |
| 18 | pqrs | abc | POI | 1 |
| 20 | pqrs | abc | ISR | 2 |
| 21 | pqrs | xyz | POA | 1 |
| 24 | pqrs | xyz | CAF | 3 |
+--------+-------------+------------+----------+---------+
where the max
version number row should be returned in combination of module_name
, mapping_id
and doc_type
.
I am unable to figure out the query. Need help.
In most databases, you would use row_number()
. In MySQL, this is not available. One method is join
and group by
:
select t.*
from t join
(select module_name, mapping_id, doc_type, max(version) as version
from t
group by module_name, mapping_id, doc_type
) tt
using (module_name, mapping_id, doc_type, version);
if we take the OP's remarks literally, or possibly just
select t.*
from t join
(select doc_type, max(version) as version
from t
group by doc_type
) tt
using (doc_type, version);
another alternative
select *
from documents d
where not exists
(
select 1 from documents dv
where dv.doc_type = d.doc_type
and dv.version > d.version
)
literally: "there is no bigger version number for same values"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.