今天我们继续给大家介绍MySQL相关知识,本文主要内容是SQL语句中基本的查询操作。

一、基本查询语句

在SQL语句中,使用select关键字进行数据的查询,后面可以跟where、order by、like、between and等关键字进行修饰,表示按照要求进行查询。
普通SQL语句查询示例如下:

select * from student;
select id,name from student;

在普通select查询语句中,select后面紧跟着的是要查询的字段,中间以逗号分割,或者是直接加*符号,表示该表中的所有字段。上述命令执行结果如下:

除了上述基本查询外,SQL语句还支持其他一些修饰的关键字,下面将会为大家一一介绍。

二、查询去重

distinct表示去重的意思,当加在select语句后面时,表示查询得到的结果如果有重复,就删掉。SQL语句示例如下:

select distinct sex from student;

使用distinct关键字和不使用该关键字执行差异如下:

三、条件查询

select查询语句经常会联合where一起做条件查询,条件可以是等于(=)、不等与(<>或!=)、与(and)、或(or)、非(not)、大于(>)、小于(<)、大于等于(>=)、小于等于(<=)、介于A和B之间(between A and B)等等。
SQL语句示例如下:

select * from student where sex='man';
select * from student where age >=20;
select * from student where age between 10 and 20;
select * from student where major<>'Math';
select from student where age>10 and sex='man';

上述五条命令分别表示:
查找student表中的男性,年龄大于等于20的人,年龄介于10到20之间的人,主修不是数学的人,和年龄大于10岁的男性。
部分命令执行结果如下:

四、模糊查询

select语句也支持模糊查询,所谓模糊查询,就是根据某一字段的部分特征机型查询,select模糊查询所使用的是like与not like关键字。SQL模糊查询使用示例如下:

select * from student where name like 'Li_';
select * from student where name like 'Li%';
select * from student where name not like 'Li%';

在模糊查询语句中,下划线表示该处匹配任意一个字符,而百分号表示该出匹配任意个数的任意字符。
命令执行结果如下:

五、空值查询

除了之前介绍的一些条件外,由于MySQL支持null的空数据出现,因此,我们在查询空数据时,需要使用null或者是not null。
SQL语句示例如下:

select * from student where major is null;
select * from student where major is not null;

执行结果如下:

六、查询排序

有时,我们需要对查询的结果进行排序,排序使用order by关键字,如果是升序排列,需要在最后附加asc,如果是降序排列,需要在最后附加desc,如果什么都不加,则默认为升序排列,SQL排序语句示例如下:

select * from student order by age;
select * from student order by age desc;

上述命令执行结果如下:

原创不易,转载请说明出处:https://blog.csdn/weixin_40228200

更多推荐

SQL语句详解(二)——select基本查询操作