1. 插入

1.1 语法

插入数据的要素:

  • 表名
  • 列名
  • 新插入的值

1.1.1 插入方式一

insert into 表名(列名, ...)
values(值1, ...);
其中,值和列名要一一对应

1.1.2 插入方式二

insert into 表名
set 列名=值, 列名=值...;

1.2 示例

insert into beauty
set id=19,
    name='姓名五',
    phone='999';
insert into beauty
values (23, '姓名6', '女', '1990-4-23', '12345123456', null, 2),
       (24, '姓名7', '女', '1990-4-23', '12345123456', null, 2),
       (25, '姓名8', '女', '1990-4-23', '12345123456', null, 2);

1.3 两种方式对比

  • 方式一支持一次插入多行,但是方式二不支持
  • 方式一支持子查询,方式二不支持

2. 修改

2.1 修改单表记录

语法:

update 表名
set 列 = 新值, 列 = 新值...
where 查找条件
and 筛选条件;

示例:

# 修改boys表中的id为2的姓名和
update boys
set boyName='张飞',
    userCP=10
where id = 2;

# 修改beauty表中姓唐的电话,都改为13800000000
update beauty
set phone = '13800000000'
where name like '唐%';

2.2 修改多表的记录

2.2.1 SQL92标准

update 表1 别名, 表2 别名
set 列 = 值, 列 = 值 ...
where 查找条件
and 筛选条件;

2.2.1 SQL99标准

update 表1 别名
inner | left | right join 表2 别名
on 连接条件
set 列 = 值, 列 = 值, ...
where 筛选条件;

示例:

update boys bo
    inner join beauty b on bo.id = b.boyfriend_id
set b.phone = '114'
where bo.boyName = 'hxy';


update boys bo
    right join beauty b on bo.id = b.boyfriend_id
set b.boyfriend_id=2
where b.id is null;

3. 删除

3.1 delete

3.1.1 单表删除

delete from 表名 where 筛选条件;

示例:

# 删除手机号以9结尾的信息
delete
from beauty
where phone like '%9';

3.1.2 多表删除

语法:

# SQL92:
delete 表1的别名
from 表1 别名, 表2 别名
where 连接条件
and 筛选条件;

#SQL99
delete 表1的别名
from 表1 别名, 表2 别名
inner | left | right join 表2 别名 on 连接条件
where 筛选条件;

示例:

delete b
from beauty b
         inner join boys bo on b.boyfriend_id = bo.id
where bo.boyName = 'hxy';

delete b, bo
from beauty b
         inner join boys bo on b.boyfriend_id = bo.id
where bo.boyName = 'hxy';

3.2 truncate

语法:

truncate table 表名;

示例:

# 删除表boys
truncate table boys;

3.3 两种方式对比

  • delete可以加where条件,truncate不能加
  • truncate删除时效率较高
  • 如果要删除的表中有自增长的列,delete删除后再插入数据,新数据的自增长列从断点开始,truncate清空数据后,新数据的自增长列从1开始
  • truncate删除没有返回值,delete删除有返回值
  • truncate删除数据后不能回滚,, delete删除数据后可以回滚
最后修改:2023 年 11 月 14 日
如果觉得我的文章对你有用,请随意赞赏