首页 > 数据库 > 数据库开发技术 > 《MySQL 入门教程》第 10 篇 数据排序
SELECT col1, col2, ...
FROM table_name
[WHERE conditions]
ORDER BY col1 [ASC | DESC];
select emp_name, hire_date
from employee
order by hire_date;
emp_name|hire_date |
---------|----------|
关羽 |2000-01-01|
张飞 |2000-01-01|
刘备 |2000-01-01|
孙尚香 |2002-08-08|
孙丫鬟 |2002-08-08|
赵云 |2005-12-19|
...
SELECT col1, col2, ...
FROM table_name
[WHERE conditions]
ORDER BY col1 [ASC | DESC], col2 [ASC | DESC], ...;
select emp_name, sex, hire_date, salary
from employee
where dept_id = 1
order by hire_date asc, salary desc;
emp_name|sex |hire_date |salary |
---------|----|----------|--------|
刘备 |男 |2000-01-01|30000.00|
关羽 |男 |2000-01-01|26000.00|
张飞 |男 |2000-01-01|24000.00|
select emp_name, salary, bonus, salary * 12 + ifnull(bonus, 0) as total_income
from employee
order by total_income;
emp_name|salary |bonus |salary * 12 + ifnull(bonus, 0)|
emp_name|salary |bonus |total_income|
---------|--------|--------|------------|
邓芝 | 4000.00| | 48000.00|
蒋琬 | 4000.00| 1500.00| 49500.00|
黄权 | 4200.00| | 50400.00|
庞统 | 4100.00| 2000.00| 51200.00|
糜竺 | 4300.00| | 51600.00|
孙乾 | 4700.00| | 56400.00|
...
select emp_name, salary, bonus, salary * 12 + ifnull(bonus, 0) as total_income
from employee
order by 4;
select emp_name, bonus
from employee
where dept_id = 3
order by bonus desc;
emp_name|bonus |
----------|-------|
孙尚香 |5000.00|
孙丫鬟 | |
select emp_name, ifnull(bonus, 0) as bonus
from employee
where dept_id = 3
order by ifnull(bonus, 0);
emp_name|bonus |
----------|-------|
孙丫鬟 | 0.00|
孙尚香 |5000.00|
select emp_name, email
from employee
where dept_id = 5
order by emp_name;
emp_name|email |
---------|--------------------|
孙乾 |sunqian@shuguo.net |
庞统 |pangtong@shuguo.com |
法正 |fazheng@shuguo.com |
简雍 |jianyong@shuguo.com |
糜竺 |mizhu@shuguo.com |
蒋琬 |jiangwan@shuguo.com |
邓芝 |dengzhi@shuguo.com |
黄权 |huangquan@shuguo.com|
select emp_name, email
from employee
where dept_id = 5
order by emp_name collate 'utf8mb4_zh_0900_as_cs';
emp_name|email |
---------|--------------------|
邓芝 |dengzhi@shuguo.com |
法正 |fazheng@shuguo.com |
黄权 |huangquan@shuguo.com|
简雍 |jianyong@shuguo.com |
蒋琬 |jiangwan@shuguo.com |
糜竺 |mizhu@shuguo.com |
庞统 |pangtong@shuguo.com |
孙乾 |sunqian@shuguo.net |
select emp_name, email
from employee
where dept_id = 5
order by convert(emp_name using gbk);
emp_name|email |
---------|--------------------|
邓芝 |dengzhi@shuguo.com |
法正 |fazheng@shuguo.com |
黄权 |huangquan@shuguo.com|
简雍 |jianyong@shuguo.com |
蒋琬 |jiangwan@shuguo.com |
糜竺 |mizhu@shuguo.com |
庞统 |pangtong@shuguo.com |
孙乾 |sunqian@shuguo.net |
select emp_name, field(emp_name, '刘备','关羽','张飞') as num
from employee
where dept_id = 1
order by field(emp_name, '刘备','关羽','张飞');
emp_name|num|
---------|---|
刘备 | 1|
关羽 | 2|
张飞 | 3|
原文作者:SQL编程思想;如有侵权,请联系管理员删除。