MySQL命令
创建数据
创建表
create table 表名(列名 类型);
查看表结构
desc 表名
删除表
drop table 表名
修改表名 DDL
alter table 旧表名 rename 新表名
修改列名
alter table 表名 change column 旧列名 新列名 类型
修改列类型
alter table 表名 modify 列名 新类型
添加列
alter table 表名 add column 新列名 类型
删除列
alter table 表名 drop column 列名
获取表的约束信息
show keys from 表名
添加唯一约束
alter table 表名 add constraint 约束名 unique(列名)
删除唯一约束
alter table 表名 drop key 约束名
添加外键约束
alter table 表名 add constraint 约束名 foreign key(列名) references 参照的表名(参照的列名)
删除外键约束
alter table 表名 drop foreign key 约束名
alter table 表名 drop index 索引名(约束名)
添加数据
插入数据
insert into 表名(列名1,列名2,列名n) values(值1,值2,值n);
insert into 表名 values(值1,值2,值n);
更新数据
update 表名 set 列名=值,列名=值,列名=值 where 条件
更新子查询时 需要多套一层
删除数据
delete from 表名 where 条件
清空表
truncate table 表名
truncate 与 delete的区别
truncate整体删除 delete 是逐条删除,truncate不写服务器log delete写服务器log。
truncate会重置自增属性 delete不会重置自增属性。
关闭事务自动提交
开启transaction机制 关闭事务自动提交
start transaction
DML语句。。。。。运行后并没有数据
需要手动提交
commit;手动提交 rollback;手动回滚
查询语句
select *|投影列 from 表名
行选择
select *|投影列 from
连字符
select concat(列名1,'需要连接的符号',列名2) from 表名
得到的值使用自己选择的符号连接
模糊查询
like "%"任意字符,"_"任意一个字符
select * from 表名 where like '%内容%';
select * from 表名 where not like '%内容%';
范围查询(between,in)
select * from 表名 where 列名 between 范围 and 范围;
select * from 表名 where 列名 in(值1,值2,值3);
空值判断
select * from 表名 where 列名 is null;
select * from 表名 where 列名 is not null;
使用order by排序
select * from 表名 order by 列名
select * from 表名 order by 列名 desc
单行函数
大小写控制函数
小写
大写
字符处理
将str1和str2字符串连接
str字符串从第pos位开始,截取长度为len的字符串
获取str的长度
获取substr在str中的位置
- lpad(str,len,padstr)/rpad(str,len,padstr)
- trim(str)
去除前面和后面的空格
去除开头的空格
去除结尾的空格
- replace(str,from_str,to_str)
将str中的from_str替换为to_str
数字函数
四舍五入指定小数的值
四舍五入保留整数
截取指定小数的值,不做四舍五入处理
取余
日期函数
系统时间 select sysdate();(下同)
系统时间
当前时间的日期
当前时间的时间
返回一个月的第几天
星期几 其中1表示星期日 2表示星期一
返回指定时间年份到今天的天数
返回date日期是星期几
转换函数
date 要转换的时间, format 要转换的模板
select data_format(now(),'%Y年%m月%d日');
将字符串转换成日期
select str_to_date('2020年10月26日','%Y年%m月%d日');
通用函数
如果值1不为空 返回值1 值1为空,返回值2
判断值1、值2是否相同,如果相等返回null,不等返回值1。
判断值1是否为真(是否不为null),如果为真,则使用值2,如果为假,则返回值3。
判断value的值是否为null,如果不为null,返回value,如果为null,则继续判断下一个value,直到返回不为null的value,或者最后一个value也为空的值
条件函数
多表连接查询
等值连接
inner join on 内连接
left join 左连接
right join 右连接
union
union all 全连接
正则查询
select 列名 from 表名 where 列名 regexp '正则表达式'
regexp binary '^a' 查找以a开头的 binary 区分大小写
regexp binary 'a$' 以a结尾
regexp '^[x-z]' x到z开头的
regexp 'a|b' 查询含有a 或b的 数据
regexp '[^gyc]' 查询不包含gyc的
regexp 'e{3}' 查询包含连续三个e的数据
regexp 'e.{3}' 查询出现e任意三次的数据 不必连续
regexp 'e.{2,3}' 查询出现e任意两次或者三次的数据 不必连续
MySQL创建索引
create index 索引名 on 表名(列名)
alter table 表名 add index 索引名(列名)
drop index 索引名 on 表名
create unique index 索引名 on 表名(列名)
创建表的主键的时候创建的
所以添加主键索引添加一个主键约束就好
只能使用创建索引组合中的列名查询 符合最左原则
create index 索引名 on 表名(列名1,列名二)
查询时 列名1=?|| 列名1=?and 列名2 = ?都生效
但直接查询 列名2=?索引不生效
添加全文索引
alter table 表名 add fulltext 索引名(列名)
删除全文索引
drop index 索引名 on 表名
使用全文索引
添加全文解析器
alter table 表名 add fulltext 索引名(列名) with parser ngram;
MySQL命令