I would like to retrieve the 2 last version of a process:
| id | name | version | souce_id | | 1 | test1 | 1.00 | 0 | | 2 | test1 | 1.01 | 1 | | 3 | test1 | 1.02 | 1 | | 4 | test1 | 1.03 | 1 | | 5 | test2 | 1.00 | 0 | | 6 | test2 | 1.01 | 4 | | 7 | test2 | 1.02 | 4 | | 8 | test3 | 1.00 | 0 |
and the expected result would be:
| id | name | version | souce_id | | 3 | test1 | 1.02 | 1 | | 4 | test1 | 1.03 | 1 | | 6 | test2 | 1.01 | 4 | | 7 | test2 | 1.02 | 4 | | 8 | test3 | 1.00 | 0 |
I have written this query but I don't like it... and I cannot include it in as a subquery in a WHERE
. id
IN (...)SELECT (SELECT SUBSTRING_INDEX(GROUP_CONCAT(
id
ORDER BY process_version
DESC), ',', 2) FROM process
WHERE process_name
= parent
. process_name
) AS ids
FROM process
AS parent WHERE 1 GROUP BY process_name
Eg
SELECT x.*
FROM my_table x
JOIN my_table y
ON y.name = x.name
AND y.id <= x.id
GROUP
BY x.id
HAVING COUNT(*) <=2;
Thanks Strawberry! With just a small correction I have my request (yours was giving the 2 1st versions):
SELECT `x`.*, `y`.`id`
FROM `my_table` AS `x`
JOIN `my_table` AS `y`
ON `y`.`name` = `x`.`name`
AND `y`.`id` >= `x`.`id`
GROUP BY `x`.`id`
HAVING COUNT(*) <=2
ORDER BY `x`.`name` ASC, `x`.`version` ASC
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.