mysql - MySQL 语句选择特定列的最新条目
问题描述
我正在使用 MySQL,并且该表是使用此架构创建的:
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`));
该表具有以下条目,如链接中所示(不允许嵌入)。
对于特定的 class_id(例如 10),我想获取所有具有最大版本的不同 type_id。有 5 个 type_id 1,2,3,4,5 可能存在或不存在,但是如果 type_id 存在于特定类中,我们需要最新的(最大版本)。查询也应该返回文本列。
如果需要,这里是插入语句
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);
解决方案
- 在派生表中获取每个 type_id 的最大版本值
- 加入主表以获取相应的行。
尝试以下操作:
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
结果
| 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 |
推荐阅读
- php - Laravel Echo Server 给出错误未处理错误事件:错误:连接 ECONNREFUSED
- html - Swift:NSAttributeString 不正确的 HTML 结果
- javascript - 返回承诺的Javascript顺序函数
- php - 数据库已连接,但数据未存储在 xamp 服务器中
- android - 切换到多窗口模式时,我的 Android 应用程序崩溃
- ios - iOS当按下按钮“下一步”加载新行表单解析Swift
- python - Python中各种数据库的单一API
- java - 从 Fragment 中的 Adapter 获取 imageview
- git - git clone 或通过慢速网络拉取一个巨大的 repo 以致命的 EOF 结束
- dataframe - Deedle F# - 查找索引组中的最大行数