【MySQL数据库】MySQL表的增删改查(1)

CRUD

注释:在SQL中可以使用"--空格+描述"来表示注释说明

CRUD既增加(create)、查询(retrieve)、更新(update)、删除(delete)。

1.新增(Create)

语法:

insert [into] 表名 values (要插入的内容);

1.1单行数据+全列插入

-- 插入两条数据,插入的数量必须和指定列数量及顺序一致
insert into student values(有几个表的列数写几个表的列数,顺序要一致);
insert into student values(有几个表的列数写几个表的列数,顺序要一致);

1.2多行数据+指定列插入

-- 插入两条数据,插入的数量必须和指定列数量及顺序一致
insert into student (id,sn,name) values
(100,2001,'n1'),
(101,2002,'n2');

2.查询(Retrieve)

语法:

select 列名 from 表名;

2.1 全列查询

--通常情况下,不建议使用*进行全列查询
-- 1.查询的列越多,意味着需要传输的数据量越大
-- 2.可能会以影响到索引的使用
select * from 表名;

2.2 指定列查询

-- 指定列的顺序不需要按定义表的顺序来
select id,name,english from 表名;

2.3 查询字段为表达式

-- 表达式不包含字段
select id,name,10 from 表名;
-- 表达式包含一个字段
select id,name,english+10 from 表名;
-- 表达式包含多个字段
select id,name,chinese+math+english from 表名;

2.4 别名

为查询结果中的列指定别名,表示返回的结果集中,以别名作为该列的名称,语法:

select 列名 [as] 别名 from 表名;
-- 结果集合中,表头的列名=别名;
select id,name,chinese +math+english 总分 from 表名;

2.5 去重:distinct

使用distinct 关键字对某列数据进行去重:

select distinct math from 表名;

2.6 排序:order by

语法:

-- asc 为升序(从小到大) 
-- desc 为降序(从大到小)
-- 默认为:asc
select … from 表名 order by 列名 [asc/desc];

1)没有order by 子句的查询,返回的顺序是未定义的,永远不要依赖这个顺序。

2)null数据排序,视为比任何值都小,升序出现在最上面,降序出现在最小面。

3)使用表达式及别名排序。

-- 查询同学及总分,由高到低
select name,chinese+english+math from exam_result order by chinese+english+math desc;
select name,chinese+english+math total from exam_result order by total desc;

4)可以对多个字段进行排序,排序优先级随书写顺序

-- 查询同学各门成绩,依次按数学降序,英语升序,语文升序的方式显示
select name,math,english,chinese from exam_result order by math desc,english,chinese;

2.7 条件查询

比较运算符:

逻辑运算符:

注:

1)where条件可以使用表达式,但不能使用别名。

2)and的优先级高于or,在同时使用时,需要使用小括号()包裹优先执行的部分。

2.8 分页查询:limit

语法:

-- 起始下标为0
-- 从0开始,筛选n条结果
select 列名 from 表名 [where …] [order by …] limit n;
-- 从s开始,筛选n条结果
select 列名 from 表名 [where …] [order by …] limit s,n;
-- 从s开始,筛选n条结果,比第二种用法更明确,建议使用
select 列名 from 表名 [where …] [order by …] limit n offset s;

3.修改

语法:

update 表名 set 列名=(变更后的值)[,列名=(变更后的值)][where…] [order by …] [limit…]

例子:

-- 将孙悟空同学的数学成绩变更为80分
update exam_result math=80 where name='孙悟空';
-- 将总成绩倒数前三的3位同学的数学成绩加上30分
update exam_result set math=math+30 oeder by chinese +math+english limit 3;
-- 将所有同学的语文成绩更新为原来的2倍
update exam_result set chinese =chinese * 2;

4.删除(Delete)

语法:

delete from 表名 [where …] [order by…] [limit …]

例子:

-- 删除张三同学的考试成绩
delete from exam_result where name ='张三';
-- 删除整张表数据
drop table if exists for_delete;
-- 删除整表数据
delete from for_delete;
发布了62 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43669007/article/details/104072069