sql - MySQL - 连接表,仅检索最大 ID

标签 sql max greatest-n-per-group

我在其他帖子上看到了类似问题的解决方案,但是我在将其应用于我的特定问题时遇到了问题。

这是我最初的加入:

SELECT service_note_task, comment_id, comment FROM service_note_task LEFT JOIN service_note_task_comments ON service_note_task.service_note_task_id = service_note_task_comments.service_note_task_id;  

结果是:
+-----------------------------+------------+--------------+
| service_note_task           | comment_id | comment      |
+-----------------------------+------------+--------------+
| This is service note task 3 |         25 | Comment      |
| This is service note task 3 |         26 | Comment Blah |
| This is service note task 3 |         36 | aaa          |
| This is service note task 2 |         13 | Awesome comm |
| This is service note task 1 |         12 | Cool Comm    |
+-----------------------------+------------+--------------+

但是对于每个 service_note_task,我真的只需要一行代表具有最高 comment_id 的评论,如下所示:
+-----------------------------+------------+--------------+
| service_note_task           | comment_id | comment      |
+-----------------------------+------------+--------------+
| This is service note task 3 |         36 | aaa          |
| This is service note task 2 |         13 | Awesome comm |
| This is service note task 1 |         12 | Cool Comm    |
+-----------------------------+------------+--------------+

我想我可以在子选择语句中使用 MAX 来缩小我想要的结果的范围。我如何将其纳入我的陈述以获得这些结果?

最佳答案

作为引用,这被称为“groupwise-maximum”

http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html

关于sql - MySQL - 连接表,仅检索最大 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14775561/

相关文章:

mysql - 使用别名时拉取多列

jquery - 如何在设置最小值或最大值后刷新 jQuery UI slider ?

mysql - SQL仅选择列上具有最大值的行

sql - postgresql:按列分组/Windows函数/最小-最大和复杂查询

mysql - 比较 MySQL 中的 TIMEDIFF

mysql - 如何让 Round() 的第二个参数与列一起使用?

sql - Postgresql 从 max tuple 获取其他信息

haskell - 为什么在 Haskell 中最大值 (8,1) = 1?

sql - T-SQL : Selecting Column Based on MAX(Other Column)

mysql - 如何在SQL中按记录类型获取最新记录