(以下主要以MySQL适用为主,Oracle略有不同但我也还不知道)
##数据库 操作
增
- 创建数据库
create database db1;
- 创建数据库时指定字符集
create database db2 character set gbk;
删
- 删除数据库
drop database db1;
改
查
- 查询所有数据库
show databases;
- 查看单个数据库详情
show create database db1;
使用/切换数据库
use db1;
##表 操作
增
- 创建表
-普通格式:create table 表名(字段名1 字段1类型,字段名2 字段类型。。。。。。);
create table person(name varchar(10),age int);
-严谨格式:create table hero(id int,name varchar(10)) engine=myisam charset=gbk;
删
- 删除表
drop table emp;
改
- 修改表名
-格式:rename table 原名 to 新名;
rename table student to t_stu;
- 修改表的引擎和字符集
-格式:alter table 表名 engine=innodb/myisam charset=utf8/gbk;
alter table t_stu engine=innodb charset=utf8;
- 添加表字段
-格式:alter table 表名 add 新字段名 类型;
alter table t_stu add chinese int first/after xx字段; ( “first:最前 / after 老子段 / 默认在最后加”)
- 删除表字段
-格式:alter table 表名 drop 字段名;
alter table t_stu drop chinese;
- 修改表字段的名称和类型
-格式:alter table 表名 change 老字段名 新字段名 新字段类型;
例: alter table t_stu change math english int;
- 修改字段类型或字段的位置
-格式: alter table 表名 modify 字段名 新类型 first/after xxx;
alter table t_stu modify english int after name;
alter table t_hero engine=innodb charset=utf8;
查
- 查看所有表
show tables;
- 查看单个表信息
-格式:show create table 表名;
show create table person;
- 查看表字段信息
desc student;
##数据 操作
增
-全表插入格式:insert into 表名 values (值1,值2,值3......);
-指定字段插入格式: insert into 表名 (字段名1,字段名2) values (值1,值2);
- 批量插入数据格式:insert into 表名 values (值1,值2,值3......),(值1,值2,值3......),(值1,值2,值3......);
- 指定字段批量格式:insert into 表名 (字段名1,字段名2) values (值1,值2),(值1,值2),(值1,值2);
删
-格式:delete from 表名 where 条件;
例:delete from emp where id=2; 例:delete from emp where age is null;
改
-格式:update 表名 set age=20 where id=1;
update emp set age=18 where id=4; update emp set name='曹操' where id=2;
查
-格式: select * from 表名;
-指定字段查询:select id,name from emp;
-条件查询格式:select * from 表名 where 条件: select * from emp where id<10;
##整理汇总:
1. 数据库相关SQL
- 创建数据库 create database 数据库的名称
- 删除数据库 drop database 数据库名
- 查询所有数据库 show databases;
- 查看单个数据 show create database 数据库名
- 创建指定字符集 create database 数据库名 character set gbk/utf8;
- 使用数据库 use 数据库名;
2. 表相关SQL
- 创建表 create table t1(id int,name varchar(10)) engine=myisam/innodb charset=utf8/gbk;
- 删除表 drop table t1;
- 查看所有表 show tables;
- 查看单个表 show create table t1;
- 查看表字段 desc t1;
- 修改表:
1. 修改表名: rename table t1 to t2;
2. 修改表属性: alter table t1 engine=myisam/innodb charset=utf8/gbk;
3. 添加表字段: alter table t1 add age int first/after xxx;
4. 删除表字段 alter table t1 drop age;
5. 修改表字段名和类型 alter table t1 change age abc int;
6. 修改类型和位置 alter table t1 modify age int first/after xxx;
3. 数据相关:
- 插入数据: insert into t1 values(值1,值2),(值1,值2),(值1,值2);
insert into t1 (字段1,字段2) values(值1,值2),(值1,值2),(值1,值2);
- 查询数据: select * from t1;
select 字段名,字段名 from t1 where 条件
- 修改数据: update t1 set age=20 where id=10;
- 删除数据: delete from t1 where id<10;