MySQL:DQL语句 数据查询select语句用法

DQL语句

查询数据库中的记录,关键字 select

Select语句1
Select [distinct] * |{字段1、字段2、字段3…} from 表名;
注:
distinct : 显示结果时,是否去除重复列,加上则去重,不加不去重,[ ]表示可加可不加
星号 : 表示所有的字段(列)

例如:
创建一张学生成绩表,有id、name、chinese、english、math 字段。
(1)、查询表中所有学生的信息
select * from student;
(2)、查询表中所有学生的姓名和对应的英语成绩。
select name,english from student;
(3)、过滤表中重复math 成绩。
select distinct math from student;

Select 语句2
1,select *|{字段1|expression、字段2|expression,…}from table;
2,select 字段 as 别名 from 表名;

注:
expression : mysql支持表达式 加减乘除;
as: 表示给某一列起别名;并且as 可以省略;

例如:
(1).在所有学生数学分数上加10分。
select name,math+10 from student; # 原表数据不会改变。
(2).统计每个学生的总分。
select name,chinese+english+math from student;
(3).使用别名表示学生总分数
select name as ‘姓名’ ,chinese+english+math as ‘总分’ from student;

Select 语句3
使用where 语句进行条件查询

(1).查询姓名为王五的学生成绩
select * from student where name=‘王五’;
(2).查询英语成绩大于90分的同学
select * from student where english>90;
(3).查询总分大于200分的所有同学
select * from student where (chinese+english+math)>200;
这里可以为chinese+english+math 取个别名total
select name ,chinese+english+math as total from student where total >200;

Select 语句4
在Where语句中经常使用的运算符
在这里插入图片描述
注: 逻辑运算符优先级 not and or;

例如:
(1).查询英语分数在 70-75之间的同学。
select * from student where english between 70 and 75;
(2).查询数学分数为80,81,82的同学。
select * from student where math in (80,81,82);
(3).查询所有姓李的学生成绩。
select * from student where name like ‘l%’;
(4).查询数学分>80并且语文分>80的同学。
select * from student where math>80 and chinese>80;

Select 语句5
使用order by 子句对结果集进行排序
语法:
Select 字段1,字段2,… from 表名 order by 字段3 asc|desc;
注:
Order by 字段 : 对那一字段(列)进行排序
asc: 升序(不写时默认), desc: 降序

例如:
(1).对数学成绩排序后输出。
select name,math from student order by math;
(2).对总分排序后输出,然后再按从高到低的顺序输出
select name as 姓名,chinese+english+math 总分 from student order by 总分 desc;
(3).对姓l的学生成绩按语文升序排序输出
select * from student where name like ‘l%’ order by chinese;

Select 语句6
limit 限制
select col_name1,col_name2… from 表名 limit {[offset,] row_count | row_count offset offset}

(1)显示student 表格中的前3行。
Select * from student limit 3;
注: 3 表示 显示前3行。
(2)显示 student 表格中的第3~5行。
Select * from student limit 2,3;
注: 2表示偏移几行,3表示显示的总行数。

总结:
(1)distinct 运算 as别名 where条件 order by limit 要学会混合运用 对数据进行查询操作
(2),select 语句条件顺序:
selec * from 表1 left join 表2 on 条件
[where 条件字句]
[group by 字句]
[having 字句]
[order by 字句]
[limit 字句]

猜你喜欢

转载自blog.csdn.net/aixiangnan/article/details/89164251