MySQL第四天

2022-09-06

1、为某个字段设置别名(as关键字)

以“students”为例:

students表的字段有:id,name,age,gender,is_del

select name as n,age as a from students;

说明:select 属性名 as 新名称,属性名2 as 新名称 from 表名;

 2、给某个字段去除重复的值,使用(distinct关键字)

以“students”为例:

select distinct gender from students;

说明:格式:select distinct 字段名 from 表名;

3、查询某个字段不等于某个值

有两种方式,使用where关键字

以“students”为例,查询姓名不为“Tom”的同学:

(1)方式一

select * from students where name != 'Tom';

(2)方式二

select * from students where name<>'Tom';

4、条件查询1(逻辑运算符and )

以“students”为例:

查询年龄大于等于18而且性别为girl的同学:

select * from students where age>=18 and gender='girl';

说明:select * from 表名 where 字段约束条件1 and 字段约束条件2;

5、条件查询2(逻辑运算符or)

以“students”为例:

查询id大于3或者性别为boy的同学:

select * from students where id > 3 or gender = 'boy';

6、查询同学中以某个姓开头的语句

select * from 表名 where name like '某姓%';

7、查询某个字段中某个连续范围的值(between...and...)

以“students”为例:

select * from students where id between 2 and 4;

8、查询某个字段中多个属性值(使用in关键字)

以“students”为例:

select * from students where name in ('Tom','Amy');

说明:格式 : select * from 表名 where 字段名 in (属性值1,属性值2);

9、查询某个字段中为null的值(使用 is null)

注意,此处不能使用 “= null”,如果使用了结果会显示查询为空

以“students”为例:

select * from students where gender is null;

10、按某个字段名排序查询(order by)

desc: 降序排序,从大到小

asc: 升序排序,从小到大,默认情况下为升序。

以“students”为例:

select * from students where age > 18 and gender = 'boy' order by id desc;

说明:select * from 表名 where 约束条件 order by 字段名 desc/asc;

(2)多次排序

以年龄降序排序,当年龄相同时,以编码升序排序

select * from students order by age desc,id asc;

11、当数据量多,一页显示不了时,使用分页查询(limit)

以“students”为例:

select * from students where gender = 'boy' limit 0,3;

说明:格式:select * from 表名 where 约束条件 limit start,count;

其中start指的是索引行,默认以0开始;count指的是每一页最多显示的条数。

 

posted @ 2022-09-06 21:58  努力是一种常态  阅读(82)  评论(0)    收藏  举报