创建:Create 查询:Retrieve 修改:Update 删除:Delete
一、insert添加数据
1、基本语法
insert into 表名 (字段)values(字段值);
2 例句
如果给所有的字段赋值 ,而且所有字段为空 直接:insert into student values(1,'张三','15','男');
如果给部分的字段赋值 insert into student (name,sex,age)values('李 四','25','男');
insert into student (name,sex,age)values('赵四','35','男'),('吴昕','24','女');
3模拟大数据
insert into student(name,score,money,age)select nmae, score,money,age form student;
二、delete删除数据
1、基本语法
delete from 表民;
2 例句
delete from student;
delete from student where xid=1;(一定不要忘记写where条件)
delete from student where age>30;
3、delete(删除)与truncate(清空)的区别:
delete:删除数据,但数据号保留
truncate:清空数据,数据号不保留
三、update修改数据
1、基本语法
update 表名 set 字段名=‘字段值’(多个字段之间用逗号分隔) where 条件
2 、例句
update student set name='王五', sex='男';
update student set age='18' where name='吴昕';
给所有员工的工资增加5%:
update student set money=money*1.05;
删除数据可以在表中添加一个是否显示字段,显示值为1,不显示值为二,
用修改来代替,防止数据删除找不回来。
四、select查询数据
1、基本语法
select * from 表名;(查询表中所有数据)
select 字段名 from 表名;(查询指定字段值)
2、 例句
删除工资最高的员工
delete from student where money=(select max(money) from (select * from student) as t);(as可写可不写)
3、 in 与 exists的区别
如果两表大小相等,那么用in和exists的都可以。
//如果子查询表大用exists,效率高。
select * from student where exists(select did form dept);
//如果子查询表小用exists,效率低。
select * from student where did in(select did form dept);
4 、limit分页
(1)基本语法:limit开始,记录数;
(2)select * form student limit 0,2;(0可以省略,表示从头开始)
(3)实际开如要注意公式:
select * form student limit (当前页数-1)*记录数,记录数;
5、 五大聚合函数
(1)max最大值
(2)min最小值
(3)avg平均值
(4)sum求和
(5)count记录函数
例句:mysql> select * from emp group by y_id having y_age>(select avg(y_age) from emp);
6、模糊语句查询
select * from student where name like '%四%';//名字含有‘四
select * from student where name like'四%';//名字以‘四’结尾
select * from studentwherenamelike'%四';//名字以‘四’开头
select * from student where name like'_四';//名字以‘四’结尾的两个字
7、排序
(1)升序(是默认的,可以省略)
select * from student order by pid asc;
(2)降序
select * from student order by pid desc;
8、分组
group by:是分组
having:是分组条件,不能单独使用,必须和group by一起使用。
例句:
select max(money) from student group by did having count(did)>1;
select * from student where money in(max(money) from student group by did havingcount(did)>1;)
多表主外键(完整性约束):
create table person (id int(3) primary key auto_increment,name varchar(20) ,money int,did int not null,foreign key (did) referenes deft(did));
更改表结构:
1、添加一列
mysql> alter table employee add money float;
2 添加一列有默认值
mysql> alter table employee add jobtime date default '2016-02-08';
3添加主键
mysql> alter table employee add primary key(money);
为表添加一个主键,如果主键已经存在,则出现错误
4添加外键
mysql> alter table employee add foreign key(money) references studet(sid);
5 删除1列
mysql> alter table student drop phone;
6修改1列
mysql> alter table student modify Ssex varchar(2);
7改列名
mysql> alter table dept change money salary int;
8改表名
mysql> alter table employee rename as emp;