计数ID小于表MySQL中的其他ID

时间:2019-04-17 12:29:51

标签: mysql

我有一个这样的表sql

post_id    point    user_id
0          1.5      1
1          1.0      1
2          1.5      2
3          0.0      3
4          1.5      4
5          1.0      1
6          1.0      2
7          1.5      1
8          0.0      2
9          1.5      3

根据上表:

  1. 用户1 具有 4 个帖子-表格中用户最多的帖子。
  2. 用户2 3 个帖子=>需要添加1个帖子。
  3. 用户3 2 个帖子=>需要添加2个帖子。
  4. 用户4 具有 1 个帖子=>需要添加3个帖子。

如何找出哪些用户的帖子少于表中帖子最多的用户,然后像这样更新表

post_id    point    user_id
0          1.5      1
1          1.0      1
2          1.5      2
3          0.0      3
4          1.5      4
5          1.0      1
6          1.0      2
7          1.5      1
8          0.0      2
9          1.5      3
NULL       NULL     2
NULL       NULL     3
NULL       NULL     3
NULL       NULL     4
NULL       NULL     4
NULL       NULL     4

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

尝试一下,可以帮助您:

SELECT user_id, GROUP_CONCAT(post_id) as postIds, SUM(point) as totalPoints,
 count(user_id) as totalPosts , 
((SELECT count(user_id) as maxtotal FROM `posts` GROUP BY posts.user_id ORDER BY maxtotal DESC LIMIT 1) - count(user_id)) as totalRemaining 
FROM `posts` 

GROUP BY posts.user_id 
HAVING totalPosts < (SELECT count(user_id) as maxtotal FROM `posts` 
GROUP BY posts.user_id ORDER BY maxtotal DESC LIMIT 1) 
ORDER BY totalPosts DESC

它已经过测试并且工作正常,请同时检查屏幕截图。 enter image description here