准备工作
增删改查是针对表来说的。
先创建一张班级薪水登记表,后面的大部分操作都将在此表基础上进行:
create table class(
id int primary key auto_increment,
sname varchar(10) not null default '',
gender char(1) not null default '',
company varchar(20) not null default '',
salary decimal(6,2) not null default 0.00,
bonus smallint not null default 0
)engine myisam charset utf8;
查看表结构:desc 表名;
增
解决什么问题:
- 往哪张表添加
- 添加哪几列
- 分别添加什么值
插入所有列
insert into class
(id, sname, gender, company, salary, bonus)
values
(1, '张三', '男', '百度', 8888.99, 235);
插入部分列
insert into class
(sname,gender, salary)
values
(‘李四’,’男’,5555.66);
#注意:这里的id列因为之前设置为自动增加,所以可以看到id列虽然没有设置,仍然有值。
插入所有列的快捷方法:
如果准备插入所有列,则可以不声明待插入的列,即,如果不声明插入的列,则理解为依次插入所有列。
insert into class
values
(3,’赵武’,’男’,’新浪’,6685.74,555);
#注意:不要犯这样的错误->id是自增型的,插入时不用为其赋值。一定要赋值!!
增加多行
insert into class
(sname,company,salary)
values
(‘刘备’,’皇室成员’,2555),
(‘孙策’,’孙子后代’,4444);
改
解决什么问题:
- 改哪张表
- 需要改哪几列
- 分别改为哪些值
- 在哪些行生效
语法:
update 表名 set
列1=新值,
列2=新值
where expr;
注:注意。“where 就只能是id=N这种形式”,是一种错误的理解。“where expression”是一个表达式,只要where表达式为真,则该行就发挥作用。
EXAMPLE: 张三从百度跳槽到锤子科技,工资升为9990元,bonus为0。
update class set
company =’锤子科技’,
salary=9990,
bonus = 0
where sname = ‘张三’;
EXAMPLE:改性别为男,且工资>8000的用户的bonus为159。
update class set
bonus = 159
where gender = ‘男’ and salary >8000;
Q:这句话是什么意思。
update class set
bonus = 100
where 1;
A:where 1指的是所有行操作判断为真。
删
解决什么问题:
- 你要删哪张表的数据
- 你要删哪些行
语法:
delete from 表名
where expr;
Q:能不能只删一张表中某一行的某一列元素?
A:NO, you can not. 可以将该元素更新为空元素
注:删除,就是指删除某一行,不存在删除一行中的某一列。
EXAMPLE:将刘备删除出class表。
delete from class
where sname = ‘刘备’;
EXAMPLE:删salary 大于8000,且性别为女的用户。
delete from class
where salary >8000 and gender = ‘女’;
查
解决什么问题:
- 查哪张表的数据
- 要选择哪些列来查询
- 要选择哪些行
语法:
select 列1,列2,列3 from 表名
where expr;
EXAMPLE:
select sname,salary,bonus from class
where id = 5;
EXAMPLE:查询所有行所有列。
select * from class;
注:*代表所有列,表名后不加where条件,则选所有行。
EXAMPLE:查询部分列所有行。
select sname,salary from class
where 1;
或者
select sname,salary from class;
EXAMPLE:查id>3的人的所有列。
select * from class
where id>3;
EXAMPLE:取部分行部分列。查id<5的人的姓名和bonus。
select sname,bonus from class
where id<5;