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

标签 mysql sql greatest-n-per-group

我已经看到很多关于此类问题的解决方案(尤其是这个 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/

相关文章:

php - mysql 查询中的分组

mysql - 存储过程中的 while 循环仅循环两次而不是 8 次

sql - 在 postgreSQL 中获取当前周

mysql - INNER JOIN 后从多个表中获取最大日期

mysql - 查询不起作用需要在 groupby 之前 orderby 吗?

php - 使用php和mysql将两个表合并到一个新表

php - 如果(mysql)做某事

mysql - 如何从 MySQL 中的电子邮件地址值返回不同的域名?

mysql - MySQL中使用窗口函数的移动平均线

php - 对于每条记录,还选择记录中具有最高值的数据