mysql - 如何获取分组行的 ID?

标签 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 ,那么第五个将被省略。所以这是逻辑:

I want to the last three rows (regardless grouping). In other word, Emm ... it's hard to say, I want to select grouped rows (but not counting in LIMIT).



知道我该怎么做吗?

最佳答案

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

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

更新:在子查询中使用 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

关于mysql - 如何获取分组行的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49668576/

相关文章:

mysql_ -> PDO |我怎样才能达到相同的结果

php - 当我在 PHP 中使用对另一个类的引用时,插入 MySQL 不起作用

sql - 两列之间的最大差异

mysql - 对外键约束感到困惑

mysql - 有没有人成功地使索引合并适用于 MySQL?

mysql - 加载数据文件错误

php - 如何正确使用password_verify()?

java - SQL 将列的每个值与另一个表中行的所有值进行比较

sql - 有没有工具可以可视化复杂的 SQL 连接?

mysql - SQL 一对一关系与扁平化