数据库操作
显示数据库
show databases;
创建数据库
create database 数据库名 default charset utf8 collate utf8_general_ci;
使用数据库
use 数据库名;
表操作
创建表
create table 表名(
列名 类型,
列名 类型
)engine=innodb default charset=utf8
![]()
是否为空
null
not null
默认值
default 666
自增(默认让数值自增)
注意:表中只能有一个自增列,且必须是索引
auto_increment primary key
主键
create table ttt(
id int not null,
num int not null,
primary key(id, num)
创建表具体参数
删除表
drop table 表名
删除定义、内容、释放空间,即把整个表删除,不留痕迹
truncate table 表名
删除内容、释放空间但不删除定义
释放空间:把id为5的数据删除,下次添加数据还是从5开始
delete from 表名
删除内容、不释放空间、不删除定义
不释放空间:把id为5的数据删除,下次添加数据从6开始
delete效率比truncate低,因为他是一行一行地删除数据
修改表
添加列
alter table 表名 add 列名 类型
删除列
alter table 表名 drop column 列名
修改列类型
alter table 表名 modify column 列名 类型
修改列名、列类型
alter table 表名 change 原列名 新列名 类型
添加主键
alter table 表名 add primary key(列名)
删除主键
alter table 表名 drop primary key
![]()
tinyint
小整数
有符号: -128 ~ 127
无符号: 0 ~ 255
注意:mysql中无布尔值,用tinyint(1)表示布尔值
int
整数
有符号: -2147483648 ~ 2147483647
无符号: 0 ~ 4294967295
bigint
大整数
有符号: -9223372036854775808 ~ 9223372036854775807
无符号: 0 ~ 18446744073709551615
decimal
准确的小数值
注意:对于精确数值计算时需要用此类型
float
单精度浮点数(非准确小数值)
double
双精度浮点数(非准确小数值)
数据类型—数值
数据类型—字符串
![]()
timestamp
2018-01-01 20:55:03
数据类型—时间
表内容操作
增
insert into 表 (列名,列名...) values (值,值,值...)
insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...)
insert into 表 (列名,列名...) select (列名,列名...) from 表
删
delete from 表
delete from 表 name='jesse' and id=4
查
select * from 表
select name,age as n from 表 where id > 1
改
update 表 set title = 'three' where id=3
范围查询
select * from 表名 where id between 4 and 5;
select * from 表名 where id in (4,5,6);
select * from 表名 where id not in (2,3,4);
select * from 表名 where id in (select id from 表);
通配符
select * from 表名 where name like 'je%' # %通配多个字符
select * from 表名 where name like 'jess_' # _通配一个字符
限制
select * from 表名 limit 10; # 前10行
select * from 表名 limit 2333,666; # 从第2333行开始的第666行
排序
select * from 表名 order by 列名 asc # 按列从小到大排,desc则是从大到小排
select * from 表名 order by 列明1 desc,列明2 asc # 按列1从大到小排,相同的话就按列2从小到大排
分组
select id,name from 表名 where id>10 group by id,name;
select * from 表名 where id >5 group by id,name order by name desc;
select name,count(name) from 表名 group by name;
注意:group by 必须在 where 之后,order by 之前
连表
select A.name,B.name from A,B where A.id = b.id
select A.id,A.name,B.name from A left join B on A.id=B.id #A表显示所有数据,如果B中无对应关系则值为null