我看到了很多关于这种问题的解决方案(尤其是这个:SQL选择只有最大值的行),但似乎都不太合适:
我有以下表格布局,即附件的版本控制,这些附件绑定在实体上:
输出应该是按group_id和entity_id分组的最大版本号,如果只需要单个entity_id的列表,则只需要一个列表。
我有以下表格布局,即附件的版本控制,这些附件绑定在实体上:
TABLE attachments
+------+--------------+----------+----------------+---------------+
| id | entitiy_id | group_id | version_number | filename |
+------+--------------+----------+----------------+---------------+
| 1 | 1 | 1 | 1 | file1-1.pdf |
| 2 | 1 | 1 | 2 | file1-2.pdf |
| 3 | 1 | 2 | 1 | file2-1.pdf |
| 4 | 2 | 1 | 1 | file1-1.pdf |
| 5 | 2 | 1 | 2 | file1-2.pdf |
| 6 | 2 | 3 | 1 | file3-1.pdf |
+------+--------------+----------+----------------+---------------+
输出应该是按group_id和entity_id分组的最大版本号,如果只需要单个entity_id的列表,则只需要一个列表。
+------+--------------+----------+----------------+---------------+
| id | entitiy_id | group_id | version_number | filename |
+------+--------------+----------+----------------+---------------+
| 2 | 1 | 1 | 2 | file1-2.pdf |
| 3 | 1 | 2 | 1 | file2-1.pdf |
| 5 | 2 | 1 | 2 | file1-2.pdf |
| 6 | 2 | 3 | 1 | file3-1.pdf |
+------+--------------+----------+----------------+---------------+
What I have come up with is this self join one:
SELECT *
FROM `attachments` `attachments`
LEFT OUTER JOIN attachments t2
ON ( attachments.group_id = t2.group_id
AND attachments.version_number < t2.version_number )
WHERE ( t2.group_id IS NULL )
AND ( `t2`.`id` = 1 )
GROUP BY t2.group_id
但是这个方案只适用于不同实体不共享相同组号的情况。不幸的是,这是必要的。
在创建视图时,我遇到了一种可行的解决方案,但在我的当前设置中不支持此解决方案。
非常感谢任何想法。谢谢!