Reputation: 355
I am using MySQL and the table was created with this schema:
CREATE TABLE `example` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`version` INT UNSIGNED NOT NULL,
`text` VARCHAR(45) NOT NULL,
`class_id` INT NOT NULL,
`tyoe_id` INT NULL,
PRIMARY KEY (`id`));
The table has the following entries as seen in the link (not allowed to embed).
For a specific class_id (for example 10) I want to get all distinct type_ids with max version. There are 5 type_id 1,2,3,4,5 that may exists or not, however if a type_id exists in a specific class we want the latest (max version). The query should return the text column as well.
In case it is needed, here are the insert statements
INSERT INTO `example1` (`id`,`version`,`text`,`class_id`,`tyoe_id`) VALUES (1,1,'text1',10,1);
INSERT INTO `example1` (`id`,`version`,`text`,`class_id`,`tyoe_id`) VALUES (2,1,'text2',10,2);
INSERT INTO `example1` (`id`,`version`,`text`,`class_id`,`tyoe_id`) VALUES (3,1,'test3',10,3);
INSERT INTO `example1` (`id`,`version`,`text`,`class_id`,`tyoe_id`) VALUES (4,1,'test4',10,4);
INSERT INTO `example1` (`id`,`version`,`text`,`class_id`,`tyoe_id`) VALUES (5,1,'test5',10,5);
INSERT INTO `example1` (`id`,`version`,`text`,`class_id`,`tyoe_id`) VALUES (6,2,'test44',10,3);
INSERT INTO `example1` (`id`,`version`,`text`,`class_id`,`tyoe_id`) VALUES (7,1,'1111',11,1);
INSERT INTO `example1` (`id`,`version`,`text`,`class_id`,`tyoe_id`) VALUES (8,1,'eferwer',12,2);
INSERT INTO `example1` (`id`,`version`,`text`,`class_id`,`tyoe_id`) VALUES (9,3,'last',10,3);
INSERT INTO `example1` (`id`,`version`,`text`,`class_id`,`tyoe_id`) VALUES (10,2,'new',10,5);
INSERT INTO `example1` (`id`,`version`,`text`,`class_id`,`tyoe_id`) VALUES (11,3,'rrrr',10,5);
Upvotes: 2
Views: 56
Reputation: 28854
Try the following:
SELECT e.*
FROM
example1 AS e
JOIN
(
SELECT type_id,
MAX(version) AS maximum_version
FROM example1
WHERE class_id = 10
GROUP BY type_id
) AS dt ON dt.type_id = e.type_id AND
dt.maximum_version = e.version
WHERE e.class_id = 10
Result
| id | version | text | class_id | type_id |
| --- | ------- | ----- | -------- | ------- |
| 1 | 1 | text1 | 10 | 1 |
| 2 | 1 | text2 | 10 | 2 |
| 4 | 1 | test4 | 10 | 4 |
| 9 | 3 | last | 10 | 3 |
| 11 | 3 | rrrr | 10 | 5 |
Upvotes: 1