mysql排序由低到高_MySQL入门系列(四)—— 排序查询

一、排序查询

语法

SELECT 查询列表

FROM 表

[WHERE 筛选条件]

ORDER BY 排序列表 【ASC】

一般ORDER BY语句放在查询语句的最后【LIMIT子句除外】

案例

案例1:查询员工信息,要求工资从高到低排序

SELECT * FROM employees ORDER BY salary DESC;

查询员工信息,要求工资从低到高排序

SELECT * FROM employees ORDER BY salary ASC;

案例2:查询部门编号>=90的员工信息,按入职时间的先后进行排序

SELECT * FROM employees WHERE department_id >= 90 ORDER BY hiredate ASC;

案例3:按年薪高低显示员工的信息和年薪【按表达式排序】

SELECT *, salary*12*(1+IFNULL(commission_pct,0)) 年薪 FROM employees ORDER BY 年薪

案例4:按姓名长度显示员工的姓名和工资【按函数排序】

SELECT LENGTH(last_name) 字节长度,last_name,salary FROM employees ORDER BY 字节长度 DESC;

案例5:查询员工信息,要求先按工资排序,再按员工编号排序【按多个字段排序】

SELECT * FROM employees ORDER BY salary ASC, employee_id DESC;

二、MySQL查询测试题

1. 查询没有奖金,且工资少于18000的salary, last_name

SELECT salary, last_name FROMemployees WHERE commission_pct IS NULL AND salary<18000;

2. 查询employees表中,job_id不为'IT'或工资为12000的员工信息

SELECT * FROM employees WHERE job_id<>'IT' OR salary=12000;

3. 查询部门departments表中涉及到了哪些位置编号

SELECT DISTINCT location_id FROM departments;

4. SELECT & FROM employees 和 SELECT * FROM employees WHERE commission_pct like '%%' and last_name like '%%' 结果是否一样?

答:若字段有null值结果则不一样

5. 查询员工的姓名和部门号和年薪,按年薪降序,按姓名升序

SELECT last_name, department_id, salary*12*(1+IFNULL(commission_pct,0)) 年薪 FROM employees ORDER BY 年薪 DESC, last_name ASC;

6. 选择工资不在8000到17000的员工姓名和工资,按工资降序

SELECT last_name, salary FROM employees WHERE salary NOT BETWEEN 8000 and 17000 ORDER BY salary DESC;

7. 查询邮箱中包含e的员工信息,并按邮箱的字节数降序,再按部门号升序

SELECT * FROM employees WHERE email LIKE '%e%' ORDER BY LENGTH(email) DESC, department_idASC;

- END -

你可能感兴趣的:(mysql排序由低到高)