查询数据库中的记录,关键字 select
格式:
select 字段1,字段2,,,from 表名 where
select * from 表名
注意:* 表示所有的字段
可以显示部分字段,如果显示哪个字段,就直接写字段的名称即可,多个字段之间使用逗号隔开。
比如:
select name,chinese from student
下面主要讲的是select的语句,在这之前先创建一张学生成绩表 student,有id、name、chinese、english、math 字段。
select 语句1:
select distinct 字段名 from 表名
distinct : 显示结果时,是否去除重复列
过滤表中重复math 成绩。
select distinct math from student;
select 语句2:
select *|{字段1|expression、字段2|expression,…}from 表名;
select column as 别名 from 表名;
expression : mysql支持表达式 加减乘除;
as: 表示给某一列起别名;并且as 可以省略;
举例:
- 在所有学生数学分数上加10分特长分。
select name,math+10 from student;
- 统计每个学生的总分。
select name,chinese+english+math from student;
- 使用别名表示学生分数
select name ,chinese+english+math 总分 from student;
select 语句3:
使用where 语句进行过滤查询,where 后面可以跟表达式;
例如:
- 查询英语成绩大于90分的同学
select * from student where english>90;
- 查询总分大于200分的所有同学
select * from student where (chinese+english+math)>200;
select 语句4:
在Where语句中经常使用的运算符
注: 逻辑运算符优先级 not and or;
- 查询英语分数在 70-75之间的同学。
select * from student where english between 70 and 75;
- 查询数学分数为80,81,82的同学。
select* from student where math in (89,90,91);
注意:in符合单个条件就可以
- 查询所有姓李的学生成绩。
select* from student where name like 'l%';
- 查询数学分>80并且语文分>80的同学。
select * from student where math>80 and chinese>80;
select 语句5:
格式:
Select 字段1,字段2,…或者* from table order by 字段 asc|desc;
使用order by 子句对结果集进行排序
注:
Order by 字段名 : 对那一列进行排序
Asc: 升序(默认), Desc: 降序
对数学成绩排序后输出。
select name,math from student Oder by math desc;
select 语句6:
select 字段1,字段2... form 表名 limit {[offset,] row_count | row_count OFFSET offset}
- 显示student 表格中的前3行。
Select * from student limit 3;
注: 3 表示 显示前3行。
- 显示 student 表格中的第3~5行。
Select * from student limit 2,3;
注: 2表示偏移几行,3表示显示的总行数。