gpt4 book ai didi

mysql - 选择最大值按两列分组的行

转载 作者:可可西里 更新时间:2023-11-01 07:03:47 24 4
gpt4 key购买 nike

我已经看到很多关于此类问题的解决方案(尤其是这个 SQL Select only rows with Max Value on a Column ),但这些似乎都不合适:

我有以下表格布局,附件的版本控制,绑定(bind)到实体:

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_ids 的列表:

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

但是这个只有在不同的实体不共享相同的组号时才有效。不幸的是,这是必要的。

我在创建 View 时遇到了一个可行的解决方案,但我当前的设置不支持它。

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

最佳答案

试试这个:

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

关于mysql - 选择最大值按两列分组的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9360078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com