如何获取分组行的ID?

时间:2018-04-05 09:17:09

标签: 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                |
+----+--------+-----------+---------+--------------------+

这是我的疑问:

SELECT * FROM notifications
WHERE belongs_to_user_id = 101
GROUP BY post_id, user_id
ORDER BY id DESC
LIMIT 3

当前输出应该是这样的:

+----+--------+-----------+---------+--------------------+
| 5  | -2     | 2         | 456     | 101                |
| 6  | -2     | 3         | 123     | 101                |
| 8  | 10     | 4         | 789     | 101                |
+----+--------+-----------+---------+--------------------+

第七行被分组,我们无法在结果中看到它。这正是问题所在。以下是预期结果

+----+--------+-----------+---------+--------------------+
| 5  | -2     | 2         | 456     | 101                |
| 6  | -2     | 3         | 123     | 101                |
| 7  | 5      | 4         | 789     | 101                |
| 8  | 10     | 4         | 789     | 101                |
+----+--------+-----------+---------+--------------------+

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

  

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

知道我该怎么做?

4 个答案:

答案 0 :(得分:2)

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

0

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

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

答案 1 :(得分:0)

请试试这个

SELECT * FROM notifications WHERE belongs_to_user_id = 101 GROUP BY id, money ORDER BY id DESC

答案 2 :(得分:0)

所以,如果我没错,你想要相关subquery

select * from table t
where belongs_to_user_id = 101 and 
      user_id = (select max(user_id) from table where post_id = t.post_id)

此外,您可以添加limit子句来限制所需的记录。

答案 3 :(得分:0)

按组显示逗号分隔的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 限制3

相关问题