提问人:Martin AJ 提问时间:4/5/2018 最后编辑:Martin AJ 更新时间:9/12/2021 访问量:9636
如何获取分组行的 ID?
How can I get ids of grouped rows?
问:
我有一张这样的表格:
// 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
我想要最后三行(无论分组)。换句话说,Emm ...很难说,我想选择分组行(但不算在内)。
LIMIT
知道我该怎么做吗?
答:
0赞
Deedar Ali Brohi
4/5/2018
#1
请试试这个
SELECT * FROM notifications WHERE belongs_to_user_id = 101 GROUP BY id, money ORDER BY id DESC
5赞
Alex Zen
4/5/2018
#2
请尝试此查询。它将获取最后三个“组”,然后提取这些组的所有行(使用联接):
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
评论
0赞
Martin AJ
4/5/2018
“它将获取最后三个”组“,然后提取这些组的所有行”..!我很高兴你明白我的意思。
0赞
Martin AJ
4/5/2018
为什么要删除查询中的子句?WHERE
0赞
Alex Zen
4/5/2018
@MartinAJ联接已筛选查询结果。您将只获得最后三post_id和user_id的行
0赞
Martin AJ
4/5/2018
我说的是WHERE belongs_to_user_id = 101
0赞
Martin AJ
4/5/2018
谢谢,只是我会问另一个查询来改进您的查询(对我来说似乎不是最佳选择,因为实际上还有多个列)。
0赞
Yogesh Sharma
4/5/2018
#3
所以,如果我没错的话,你想要相关性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
11赞
Gopal Rathod
4/5/2018
#4
它按组显示逗号分隔的 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
评论
0赞
rakeshyadvanshi
1/27/2021
MySQL中最好的一个,而不是编写嵌套查询
评论