小编典典

选择具有两列分组的“最大值”的行

sql

我已经看到了很多解决此类问题的解决方案尤其是此SQL仅选择在Column上具有Max
Value的行,但是似乎没有一个合适的解决方案:

我有以下表格布局,即附件的版本控制,这些附件绑定到实体:

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   |
+------+--------------+----------+----------------+---------------+

我想出的是这种自我加入:

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

但是,只有在不同的实体不共享相同的组号的情况下,此选项才有效。不幸的是,这是必要的。

创建视图时遇到了一个可行的解决方案,但是当前设置不支持此功能。

任何想法都受到高度赞赏。谢谢!


阅读 173

收藏
2021-04-22

共1个答案

小编典典

试试这个:

select t1.* from attachments t1
left join attachments t2
on t1.entity_id = t2.entity_id and t1.group_id = t2.group_id and
   t1.version_number < t2.version_number
where t2.version_number is null
2021-04-22