表字段類型
- 數值
int 整型
float 浮點型
- 字符串
char 小字符串
varchar 大字符串
text 文本
數據字段屬性
1. unsigned 無符號
2. zerofill 默認設置無符號,不夠位數可以在前面添加零補齊
3. auto_increment 自增長(前提是必須是主鍵)
4. null 允許為空
5. not null 不允許為空
6. default 默認值
7. commit 注釋
表索引
- 索引的作用是提高檢索的速度
- 主鍵索引
//增加主鍵索引 primary key(字段); //刪除主鍵索引 //先刪除自增 alter table 表名 modify 字段 int unsigned not null; //再刪除索引 alter table 表名 drop primary key; - 唯一索引
//增加唯一索引 alter table 表名 add unique 別名(字段名); //刪除唯一索引 alter table 表名 drop index 別名; - 普通索引
//增加普通索引 alter table 表名 add index 別名(字段名); //刪除普通索引 alter table 表名 drop index 別名;
修改數據表字段
- 增加字段
alter table 表名 add 字段名 字段屬性;
//加在某個字段后面
alter table 表名 add 字段名 字段屬性 after 字段名;
//加在開頭
alter table 表名 add 字段名 字段屬性 first;
- 刪除字段
alter table 表名 drop 字段名
3.修改字段
//改字段名
alter table 表名 change 原字段名 新字段名 字段屬性;
//改字段屬性
alter table 表名 modify 字段名 字段屬性;
把表打印結果以行的形式顯示
desc select *from 表名 where 條件\G
結構化語句
- 定義語言DDL
create,drop,alter
- 操作語言DML
insert,update,delete
- 查詢語言DQL
select
- 控制語言DDL
grant,commit,roolback
數據表操作
- 增
insert
insert into 表名(字段名1,字段名2) values(值1,值2);
- 刪
delete
//不會改變自增順序
delete from 表名 where 條件;
//清空自增順序
truncate 表名;//清空表(慎用)
3.改
update
//如果不指定條件的話,則全部修改
update 表名 set 字段名=值 where 條件;
4.查
- 常規(guī)查詢
select
//查詢所有
select * from 表名;
//查詢指定數據
select 字段 from 表名;
//查詢指定條件下的指定字段
select 字段名 from 表名 where 條件;
//使用in方法指定條件
select * from 表名 where 字段名 in();
- 為查詢字段起別名
select 字段 別名 from 表名;
select 字段 as 別名,字段 from 表名;
- distinct關鍵字的使用
//過濾重復的
select distinct 字段 from 表名;
- 查詢空值
select * from 表名 where 字段 is null;
select * from 表名 where 字段 is not null;
- between and的使用
select * from 表名 where between 1 and 5;
- in的使用方法
select * from 表名 where id in(1,2,8);
//等價于
select * from 表名 id = 1 or id = 2 or id = 8;
- like的使用方法
//匹配所有 _ 匹配一個字符串
select * from 表名 where 字段名 "%匹配字符%";
//%在前,字段的索引會失效
//可以使用正則搜索(效率相對like低)
select * from 表名 where 字段名 regexp ".*匹配字符.*";
select * from 表名 where 字段名 regexp "匹配字符 | 匹配字符";
//以匹配條件開頭的
select * from 表名 where 字段名 regexp "^匹配字符";
//以匹配條件結尾的
select * from 表名 where 字段名 regexp "匹配字符$";
- 使用order by對查詢結果排序
//默認是升序,數字從小到大
select * from 表名 order by 字段名 asc;
//降序,數組從大到小
select * from 表名 order by 字段名 desc;