mysql 常用语句

新增字段

ALTER TABLE tableName ADD colName tinyint(1); 

ALTER TABLE `xxxxxx` ADD  `filedName` varchar(63) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '一些注释';

修改字段

alter table tableName modify column colName TINYINT(1);

修改主键

alter table `xxxxx` drop primary key, add primary key(`a1`,`a2`,`a3`);

新增索引

ALTER TABLE `xxxxxx`  ADD INDEX `indx_name` (`a1`, `a2`, `a3`);

修改字段的位置

mysqldump同步的时候用的到

alter table `xxxxx`  modify `PlatForm` varchar(63) after `Menu`

char_length函数

char_length 根据字符的长度进行排序

select * from brand where name like '%苏三%' 
order by char_length(name) asc limit 5;

locate 函数

instr和position函数,它们的功能跟locate函数类似

先按长度排序,小的排在前面。如果长度相同,则按关键字从左到右进行排序,越靠左的越排在前面。

select * from brand where name like '%苏三%' 
order by char_length(name) asc, locate('苏三',name) asc limit 5,5;

REPLACE 函数

update brand set name=REPLACE(name,'A','B') 
where id=1;

该函数还能替换json格式的数据内容,真的非常有用。

now函数

select now() from brand limit 1;    -- 2022-12-12 12:12:12
select now(3) from brand limit 1;  -- 2022-12-12 12:12:12.728  获取到毫秒

行锁 设置

begin;
select * from `user` where id=1 
for update;

update `user` set score=score-1 where id=1;
commit;

for update锁住一行记录,其他事务就不能在该事务提交之前,去更新那一行的数据。 注意的是for update前的id条件,必须是表的主键或者唯一索引,不然行锁可能会失效,有可能变成表锁。

查看完整的表语句

show create table `order`;

备份某张表

create table order_2022121820 
select * from `order`;

show processlist

命令查看当前线程执行情况

从执行结果中,我们可以查看当前的连接状态,帮助识别出有问题的查询语句。

id 线程id User 执行sql的账号 Host 执行sql的数据库的ip和端号 db 数据库名称 Command 执行命令,包括:Daemon、Query、Sleep等。 Time 执行sql所消耗的时间 State 执行状态 info 执行信息,里面可能包含sql信息。

备份远程数据库中的数据库:

mysqldump -h 192.22.25.226 -u root -p123456 dbname > backup.sql

explain 查看mysql的执行计划

explain select * from `order` where code='002';
id :  select唯一标识)
select_type : select 类型
table : 表名称
partitions : 匹配的分区
type : 连接类型
possible_keys : 可能的索引选择
key : 实际用到的索引
key_len : 实际索引长度
ref :  与索引比较的列
rows : 预计要检查的行数
filtered : 按表条件过滤的行百分比
extra :  附加信息

sql语句没有走索引,排除没有建索引之外,最大的可能性是索引失效了。

索引失效常见原因
  • 不满足最左前缀原则
  • 范围索引没有放最后
  • 3.使用了select *
  • 4.索引列上有计算
  • 5.索引列上使用了函数
  • 6.字符类型没有加引号
  • 7.用is null 和is not null 没有注意字段是否允许为空
  • 8.like查询左边有%
  • 9.使用or关键字时没有注意

作者:spike

分类: Mysql

创作时间:2023-06-25

更新时间:2024-12-09

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1