根据指定的列对结果集进行排序。
排序结果默认为升序,如果需要降序排列,需要使用 desc 关键字
desc 关键字示例:
select id,name from admin order by id ;
结果是:
| id | name |
+----+--------+
| 1 | gsh |
| 7 | admin |
| 10 | leo |
| 11 | nemo |
| 12 | taozi |
| 13 | mj001 |
| 14 | zzl005 |
+----+--------+
加上 desc 关键字后:
select id,name from admin order by id desc;
+----+--------+
| id | name |
+----+--------+
| 14 | zzl005 |
| 13 | mj001 |
| 12 | taozi |
| 11 | nemo |
| 10 | leo |
| 7 | admin |
| 1 | gsh |
+----+--------+
抽象SQL 语句(单字段排列):
select * from table_name order by column_name;
上面是针对单字段的排列,也可以根据多个列对结果进行排序,优先顺序按从左到右的列依次降低:
抽象SQL 语句(多字段排列):
select * from table_name order by column_name1, column_name2, column_name3;
依次按照column_name1
,column_name2
和column_name3
对结果进行排序
group by 的作用是结合合计函数,根据一个或多个列对结果集进行分组。
如果我们需要查看订单表中每个顾客的所有订单价格
相应的 SQL 语句
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
group by 有一个原则,就是 select 后面的所有列中,没有使用聚合函数的列,必须出现在 group by 后面。
即在select指定的字段要么就要包含在Group By语句的后面,作为分组的依据;要么就要被包含在聚合函数中。
sql 语句:
select cid,uid,count(title) from doc group by all cid,uid;
错误语句示例:
select cid,count(title) from doc group by cid where cid < 100;
正确的语句为:
select cid,count(title) from doc where cid < 100 group by cid;
说明:
错误语句示例:
select cid,count(title) from doc having count(title) > 20 group by cid;
正确的语句为:
select cid,count(title) from doc group by cid having count(title) > 20;
说明:
总结:
相关文章推荐: