SQLite 的 ORDER BY 子句是用来基于一个或多个列按升序或降序顺序排列数据。
语法
ORDER BY 子句的基本语法如下:
SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC];
- ASC 默认值,从小到大,升序排列
- DESC 从大到小,降序排列
您可以在 ORDER BY 子句中使用多个列,确保您使用的排序列在列清单中:
SELECT select_list FROM table ORDER BY column_1 ASC, column_2 DESC;
column_1 与 column_2 如果后面不指定排序规则,默认为 ASC 升序,以上语句按 column_1 升序,column_2 降序读取,等价如下语句:
SELECT select_list FROM table ORDER BY column_1, column_2 DESC;
实例
假设 COMPANY 表有以下记录:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0
下面是一个实例,它会将结果按 SALARY 升序排序:
sqlite> SELECT * FROM COMPANY ORDER BY SALARY ASC;
这将产生以下结果:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 7 James 24 Houston 10000.0 2 Allen 25 Texas 15000.0 1 Paul 32 California 20000.0 3 Teddy 23 Norway 20000.0 6 Kim 22 South-Hall 45000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0
下面是一个实例,它会将结果按 NAME 和 SALARY 升序排序:
sqlite> SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;
这将产生以下结果:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000.0 5 David 27 Texas 85000.0 7 James 24 Houston 10000.0 6 Kim 22 South-Hall 45000.0 4 Mark 25 Rich-Mond 65000.0 1 Paul 32 California 20000.0 3 Teddy 23 Norway 20000.0
下面是一个实例,它会将结果按 NAME 降序排序:
sqlite> SELECT * FROM COMPANY ORDER BY NAME DESC;
这将产生以下结果:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 3 Teddy 23 Norway 20000.0 1 Paul 32 California 20000.0 4 Mark 25 Rich-Mond 65000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 5 David 27 Texas 85000.0 2 Allen 25 Texas 15000.0
关于 order by 后面有多个 column 时的排序问题:
select * from company order by salary,name desc; id name age address salary ---------- ---------- ---------- ---------- ---------- 7 James 24 Houston 10000.0 2 Allen 25 Texas 15000.0 3 Scy 30 Beijng 20000.0 1 Paul 32 Califonia 20000.0 6 Kim 22 South-Hall 45000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0
- 上面的排序优先按照salary降序排列
- 排序中有两个salary值相同的 id分别是3和1
- 然后这两条记录再按照name字段降序排列
总结:
有多个排序字段时,优先按照前面的排序,如果前面的排序中有值相同的,后面的字段才起作用,在这些值相同的记录中,按照后续字段排序!