mysql 常用查询

1.unix时间戳的使用

unix_timesamp、from_unixtime 函数 和 datatime_format函数。

// 从datetime 类型取做整形 unixtime时间戳;

select unix_timestamp( datetime ) from examplestables;

// 从整形转换成datetime类型,时间格式

select from_unixtime( datetime ) from exampletables;

// 对unix 时间戳自定义时间段分组统计 distinct 不重复 dateformat 时间串自定义格式输出

select count(distinct(roleid)), dateformat( from_unixtime(datetime),"%Y-%m-%d"  ) days from tmptable  group by days;

// 表合并 重复键值的时候只更新不报错

insert into tmptable2 select * from tmptable on duplicate key update set A=a;

// 查询结果字符串拼接

select concat("s1_", strName ) from tmptable; 

2. sleep连接超时时间 --避免过多的sleep连接占用资源

 set global wait_timeout=305;

3.创建索引 表不加主键,不加索引的查询非常慢
create index idx_datarow on exampletables(datarow);

4.myisam 引擎 和 innodb引擎

myisam在 update insert 使用表级锁

innodb 在update ,insert时使用 的是按照索引和键值的行级锁,并发性更高

innodb 在创建的表行属性 为fixed的时候,blob类型字段过长,过多会报错。

Row size too large. The maximum row size for the used table type, not counting BLOBs, is 1982. You have to change some columns to TEXT or BLOBs。

需要改成dynamic。动态长度的行数据。

5.查询某列数据重复的数据值 exampletables  表中,exrow行重复的列

select * from exampletables where exrow in ( select exrow from exampletables group by exrow  having count(exrow) > 1 );

6.修改表的引擎,修改表的列类型

alter table exampletable ENGINE=InnoDB;

alter table exampletable modify column exrowname varchar(64);

7.查看正在执行的sql命令,show processlist 

select * from information_schema.processlist where command <> 'Sleep';

8.查看慢查询日志,有助于捕捉耗时查询,异常查询

show variables like 'slow';

log-slow-queries=/data/mysqldata/slowquery。log
long_query_time=2

9.GTID(Global Transaction ID)是对于一个已提交事务的编号,并且是一个全局唯一的编号。
GTID实际上是由UUID+TID组成的。其中UUID是一个MySQL实例的唯一标识。TID代表了该实例上已经提交的事务数量,并且随着事务提交单调递增。下面是一个GTID的具体形式

3E11FA47-71CA-11E1-9E33-C80AA9429562:23

9.mysql 备份--set-gtid-purged=OFF  是忽略 变量中记录的是本机上已经执行过,但是已经被purge binary logs to命令清理的gtid_set

mysqldump -uexuser -p -h127.0.0.1 --databases --no-data dbname   --set-gtid-purged=OFF  >/data/bk.sql

附上备份和恢复脚本:命令行执行

mysqldump -uroot -p -h 11.111.111.111 -P3306 --default-character-set=utf8 --set-gtid-purged=OFF --password --databases test > /home/sqlbackup

mysql -h11.111.111.111 -uroot -P3306 -p --default-character-set=utf8  < /home/sqlbackup

注意,上述脚本中,备份的部分要加入--set-gtid-purged=OFF参数,防止在备份出的sql脚本中生成 SET @@global.gtid_purged 语句:

Warning: A partial dump from a server that has GTIDs will by default include the GTIDs of all transactions, even those that changed suppressed parts of the database. If you don't want to restore GTIDs, pass --set-gtid-purged=OFF.

官方文档关于set-gtid-purged是这样写的:

This option enables control over global transaction ID (GTID) information written to the dump file, by indicating whether to add a SET @@global.gtid_purged statement to the output.

10.查询目前的 执行非sleep命令

select * from information_schema.processlist where command <>'Sleep'; 

原文地址:https://www.cnblogs.com/liulebao/p/4768051.html