在mysql中实现先分组后排序的方法
在mysql中实现按实际大小进行排序的方法
1.首先,在命令行中启动MySQL服务;
service mysql start
2.MySQL服务启动后,在命令行中输入mysql的用户名和密码登录到MySQL;
mysql -u root -p
3.登录到MySQL后,选择使用一个数据库;
use mysql;
4.最后,进入到数据库后,对数据表中的数据进行先分组后排序;
如何表结构如下:
+----+------+--------+--------------+
| id | Name | Salary | Departmentld |
+----+------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Henry| 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Mark | 90000 | 1 |
+----+------+--------+--------------+
执行以下命令即可实现先分组后排序
SELECT
a.max AS salary,
b.`name` AS employee,
c.depName AS departId
FROM
(SELECT MAX(salary) max FROM cs_employee t WHERE t.departId is NOT NULL GROUP BY t.departId ) a
LEFT JOIN cs_employee b ON a.max = b.salary
LEFT JOIN cs_depart c ON b.departId = c.id
ORDER BY b.departId