您的位置:首页 > 博客中心 > 数据库 >

MySQL自学篇(十一)

时间:2022-03-14 04:48

数据查询

一、单表查询

1、在select语句中使用“*”表示查询所有字段

首先:

创建一张表,由于测试

 create table student(id int primary key not null,name varchar(30),sex varchar(4),class varchar(10));

其次:

插入数据,用于下面的查询操作

 insert into student(id,name,sex,class) values (01,‘张三‘,‘男‘,‘班级1‘),(02,‘李四‘,‘男‘,‘班级2‘),(03,‘王五‘,‘女‘,‘班级3‘);

再次:

查询所有字段

select * from student;

 

2、在select中指定所有字段名,顺序可以和表中的顺序不同

 select name,id,class,sex from student;

 

查询所得结果是sql按照sql语句中指定的字段名排序的

3、加入where子句的查询条件

select id,name from student where class=‘班级1‘;

 

4、带有IN关键字的查询

 select * from student where id in (1,2);

 

5、带BETWEEN AND的范围查询

select * from student where id between 1 and 3;

 

6、带有LIKE的字符匹配查询

(1)‘%’,匹配任意长度的字符,甚至包括0字符

select * from student where class like ‘班%‘;

 

(2)带‘_’,一次只能匹配任意一个字符

 select * from student where class like ‘_级_‘;

 

7、查询空值

使用IS NULL子句,判断某字段内容是否为空

select name from student where id is null;

 

IS NOT NULL子句的作用跟IS NULL相反,判断某字段的内容不为空值

select name from student where id is not null;

 

 

8、带有AND的多条件查询

在select查询的时候,可以增加查询的限制条件,这样可以使得查询的结果更加精确。AND就可以增加多个限制条件。

select * from student where sex = ‘男‘ and class = ‘班级1‘;

 

 

9、带有OR的多条件查询

OR表示只要满足其中的一个条件的记录既可以返回

select * from student where sex = ‘女‘ or id = 1;

 

 

10、DISTINCT关键字使得查询的结果不重复

select distinct sex from student;

 

11、对查询的结果进行单列排序

Order by表示按照某一列排序,默认的属性是升序排序,可以使用desc实现倒序排序

select * from student order by id desc;

 

 

 

12、多列排序

select * from student order by id,class;

首先按照id的升序排序,如果遇到id相同的值,则再按照class值排序。



技术分享

热门排行

今日推荐

热门手游