目录
一、基础语法
1、数据库
CREATE DATABASE dbname
- 选择要操作的数据库
USE dbname
- 显示数据库
SHOW DATABASES;
- 删除数据库
drop database dbname;
2、表
- 创建表
create table dept(deptno int(2),deptname varchar(20));
- 修改表
--修改字段类型
alter table emp modify ename varchar(20);
--添加新字段
alter table emp add age int(3);
--指定位置添加字段
alter table emp add birth date after ename;
--添加字段到第一列
alter table emp add birth date first;
--删除列
alter table emp drop age;
--修改列名
alter table emp change age age1
- 删除表
drop table tbname;
- 显示表
--显示创建表的sql \G:记录按照字段竖着排列
show create table emp \G;
--显示表信息
desc tbname;
3、记录操作
- 插入
insert into emp(ename,hiredate,sal,deptno) values('zx','2000-01-01','5000',1)
insert into dept values(1,'tech'),(2,'sal'),(3,'fin')
- 修改
--修改数据记录
update emp set ename='zd' where ename='zx';
--同时修改多张关联表的数据记录
update emp a,dept b set a.sal = a.sal*b.deptno,b.deptname=a.ename where a.deptno = b.deptno
- 删除
delete from dept where deptno=3;
--删除多张关联表记录
delete a,b from emp a,dept b where a.deptno=b.deptno and b.deptno=3;
- 查询
--查询表所有记录
select * from emp;
--查询不重复的记录
select distinct deptno from emp;
--条件查询
select * from emp where deptno =1;
--排序 asc desc 默认升序
select * from emp order by sal;
--分页
select * from emp order by sal limit 1,3;
--聚合
select deptno,count(1) from emp group by deptno;
--聚合后汇总
select deptno,count(1) from emp group by deptno with rollup;
--聚合后过滤
select deptno,count(1) from emp group by deptno having count(1)>1