Mysql中根据子表的分组后的最大统计数获取主表中的信息

时间:2021-11-01 15:11:14
  • 连接mysql :mysql -h主机地址 -u用户名 -p密码
  • 修改密码 :mysqladmin  -u用户名 -p旧密码 password 新密码


  • 显示当前的数据库 :select database();

  • 显示数据库版本 :select version();

  • 获取当前时间: select now();


         ...................还有简单的数据库操作不做例举


下面尝试一些数据库中相对比较复杂的查询语句。

案例1:我想获取某一个学生的全部信息,该学生的发帖数量最多。学生与帖子是俩个表,帖子关联学生的主键stu_id;

俩张表中的内容如下:

mysql> select pp_id,pp_title,stu_id from tb_postpage;
+-------+-----------+--------+
| pp_id | pp_title  | stu_id |
+-------+-----------+--------+
|     1 | sdfasf    |      1 |
|     2 | 一起啊    |      1 |
|     3 | sfsdg     |      1 |
|     4 | jiayia    |      2 |
|     6 | dasfasf   |      2 |
|     7 | fasdfasdf |      3 |
|     8 |           |      3 |
+-------+-----------+--------+
7 rows in set

mysql> select stu_id,stu_count,stu_password from tb_student;
+--------+-----------+--------------+
| stu_id | stu_count | stu_password |
+--------+-----------+--------------+
|      1 | 123456    | 123456       |
|      2 | 140950105 | 051315       |
|      3 | 13145     | pangjiafnei  |
+--------+-----------+--------------+

1.先要对tb_postpage做一个分组。

  select * from tb_postpage group by stu_id;

   select pp_id,pp_title,stu_id from tb_postpage group by stu_id;
+-------+-----------+--------+
| pp_id | pp_title  | stu_id |
+-------+-----------+--------+
|     1 | sdfasf    |      1 |
|     4 | jiayia    |      2 |
|     7 | fasdfasdf |      3 |
+-------+-----------+--------+
3 rows in set

2.获得每组分组之后的计数以及stu_id

mysql> select stu_id,count(*) as count from tb_postpage group by stu_id;
+--------+-------+
| stu_id | count |
+--------+-------+
|      1 |     3 |
|      2 |     2 |
|      3 |     2 |
+--------+-------+
3 rows in set

3.获取count中的最大值

mysql> select stu_id,max(count) from (select stu_id,count(*) as count from tb_postpage group by stu_id) aa;
+--------+------------+
| stu_id | max(count) |
+--------+------------+
|      1 |          3 |
+--------+------------+
1 row in set【注意,这里要为表起一个别名

4.获取该表中的stu_id;

mysql> select stu_id from (select stu_id,max(count) from (select stu_id,count(*) as count from tb_postpage group by stu_id) aa) bb;
+--------+
| stu_id |
+--------+
|      1 |
+--------+
1 row in set


5.通过该id获取学生的全部信息

mysql> select stu_id,stu_count,stu_password from tb_student where stu_id = (select stu_id from (select stu_id,max(count) from (select stu_id,count(*) as count from tb_postpage group by stu_id) aa) bb);
+--------+-----------+--------------+
| stu_id | stu_count | stu_password |
+--------+-----------+--------------+
|      1 | 123456    | 123456       |
+--------+-----------+--------------+
1 row in set