检索数据(SELECT)
检索数据
1.检索单个列
select stu_name from students; 利用select语句从students表中检索一个名为stu_name的列
2.检索多个列
select stu_id,stu_name,stu_age from students; 从学生表中检索学生ID,姓名,年龄三列
注:当心逗号,在检索多个列的时候,一定要在列名之间加上逗号,但最后一个列名后不加,如果加了会报错误。
3.检索所有列
select * from students; 如果给定通配符*,则返回表中所有列。顺序一般是列在表在定义中出现的顺序。
注:一般,除非确实需要表中的每个列,否则最好别用通配符。虽然简单省事,但会降低检索和应用程序性能。
优点:使用通配符能检索出名字未知的列。
4.检索不同的行
select distinct stu_id from students; distinct关键字,只返回不同的值。
注:使用distinct关键字必须放在列名前面。
5.限制结果
select stu_name from students limit 5; limit子句,指定表中返回不多于五行。
注:带一个值得limit子句总是从第一行开始。
select stu_name from students limit 5,5; limit5,5指示MySQL返回从行5开始的5行
注:1.第一个数为开始位置,第二个数为要检索的行数
2.行0 检索出来的第一行为行0而不是行1(类似数组下标从零开始)
3.limit 1,1 将检索出第二行而不是第一行
4.在行数不够时,指定的检索行数为检索的最大行数
6.使用完全限定的表名
select students.stu_name from students; 等于第一条语句,但这里指定了一个完全限定的列名
select students.stu_name frim lamp149.studetns; 表名也可以完全限定
排序检索
select stu_name,stu_score from students;检索出来的数据没有特定的顺序(并不是纯随机显示,一般以在底层表中出现的顺序显示)
子句:SQL语句由子句构成名,有些子句是必须的,而有些子句是可选的。
排序输出子句:order by子句
1.MySQL对stu_name列以字母顺序排列(符号,数字,字母)
select stu_name from studetns order by stu_name;
2.以成绩升序排列
select stu_name,stu_score from students order by stu_score asc;
select stu_name,stu_score from students order by stu_score;
3.以成绩降序排列
select stu_name,stu_score from students order by stu_score desc;
注:与desc相反的是asc升序,由于默认是升序,所以一般没有写出(为了方便阅读提高代码可读性,建议写上)
4.联合排序
先按成绩再按姓名字母排序。注:仅在具有多个相同的成绩值时才按姓名,若成绩都不同则不按姓名排序。
select stu_id,stu_score,stu_name from students order by stu_score,stu_name;
5.使用order by 和limit 组合,能够找出一个列中最高或最低值
select stu_score from students order by stu_scote desc limit 1; 获得最大值
select stu_score from students order by stu_scote asc limit 1; 获得最小值
注:使用 order by 子句时,应该保证它位于from子句之后,如果使用了limit,它必须位于order by 之后,使用子句次序不会报错。
子句次序:
select->from->where->group by->having->order by->limit