如何获取分组行的 id?

Mar*_* AJ 8 mysql sql

我有一个这样的表:

// notifications
+----+--------+-----------+---------+--------------------+
| id | money  | post_id   | user_id | belongs_to_user_id |
+----+--------+-----------+---------+--------------------+
| 1  | 5      | 1         | 123     | 101                |
| 2  | 10     | 2         | 123     | 101                |
| 3  | -2     | 4         | 456     | 101                |
| 5  | -2     | 2         | 456     | 101                |
| 6  | -2     | 3         | 123     | 101                |
| 7  | 5      | 4         | 789     | 101                |
| 8  | 10     | 4         | 789     | 101                |
+----+--------+-----------+---------+--------------------+
Run Code Online (Sandbox Code Playgroud)

这是我的查询:

SELECT * FROM notifications
WHERE belongs_to_user_id = 101
GROUP BY post_id, user_id
ORDER BY id DESC
LIMIT 3
Run Code Online (Sandbox Code Playgroud)

当前的输出应该是这样的:

+----+--------+-----------+---------+--------------------+
| 5  | -2     | 2         | 456     | 101                |
| 6  | -2     | 3         | 123     | 101                |
| 8  | 10     | 4         | 789     | 101                |
+----+--------+-----------+---------+--------------------+
Run Code Online (Sandbox Code Playgroud)

第七行已分组,我们在结果中看不到它。这正是问题所在。这是预期的结果

+----+--------+-----------+---------+--------------------+
| 5  | -2     | 2         | 456     | 101                |
| 6  | -2     | 3         | 123     | 101                |
| 7  | 5      | 4         | 789     | 101                |
| 8  | 10     | 4         | 789     | 101                |
+----+--------+-----------+---------+--------------------+
Run Code Online (Sandbox Code Playgroud)

如果我删除GROUP BY,那么第五个将被省略。所以逻辑是这样的:

我想要最后三行(无论分组)。换句话说,Emm ...很难说,我想选择分组行(但不计入LIMIT)。

知道我该怎么做吗?

Gop*_*hod 11

它显示按组以逗号分隔的 id

SELECT 
  GROUP_CONCAT(id),
  post_id 
 FROM notifications 
 WHERE belongs_to_user_id = 101 
 GROUP BY post_id, user_id
 ORDER BY id DESC 
 LIMIT 3
Run Code Online (Sandbox Code Playgroud)


Ale*_*Zen 5

请尝试这个查询。它将获取最后三个“组”,然后提取这些组的所有行(使用联接):

SELECT t.*
  FROM notifications t
 INNER JOIN (SELECT s.post_id, s.user_id
               FROM notifications s
              WHERE belongs_to_user_id = 101
              GROUP BY post_id, user_id
              ORDER BY post_id DESC, user_id DESC
              LIMIT 3) u
    ON u.post_id = t.post_id
   AND u.user_id = t.user_id
 WHERE t.belongs_to_user_id = 101
 ORDER BY t.id
Run Code Online (Sandbox Code Playgroud)

更新:在子查询中使用 DISTINCT 的相同查询:

SELECT t.*
  FROM notifications t
 INNER JOIN (SELECT DISTINCT s.post_id, s.user_id
               FROM notifications s
              WHERE belongs_to_user_id = 101
              ORDER BY post_id DESC, user_id DESC
              LIMIT 3) u
    ON u.post_id = t.post_id
   AND u.user_id = t.user_id
 WHERE t.belongs_to_user_id = 101
 ORDER BY t.id
Run Code Online (Sandbox Code Playgroud)