mysql常用sql(2)

mysql常用sql(2)

创建全文索引
CREATE TABLE article (
id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
title VARCHAR(200),
content TEXT,
FULLTEXT (title, content) --在title和content列上创建全文索引
);

sql优化(in和exists的区别)
如果查询的两个表大小相当,那么用in和exists差别不大。
如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in:
例如:表A(小表),表B(大表)

1:
select * from A where cc in (select cc from B) 效率低,用到了A表上cc列的索引;
select * from A where exists(select cc from B where cc=A.cc) 效率高,用到了B表上cc列的索引。
相反的

2:
select * from B where cc in (select cc from A) 效率高,用到了B表上cc列的索引;
select * from B where exists(select cc from A where cc=B.cc) 效率低,用到了A表上cc列的索引。

not in 和not exists如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。所以无论那个表大,用not exists都比not in要快。

分析mysql_bin日志
mysql:show binlog events in 'mysql-bin.000010';

/opt/mysql/bin/mysqlbinlog --no-defaults --base64-output=DECODE-ROWS -v /ssd0/logs/mysql/mysql-bin.000016 --start-datetime='2018-12-3 9:00:00' >/ssd0/20181203.log
--no-defaults 取消默认
--base64-output=DECODE-ROWS -v 解码(解决乱码问题)
--start-datetime='2018-11-14 18:00:00' 开始时间

常用的sql

计算年龄:
比如92.10.1生日,2019.1.18时,年龄为26岁
select TIMESTAMPDIFF(year,STR_TO_DATE(csny,'%Y%m%d'),CURDATE()),csny from t_user_lisk;
只按年份相减,上面情况,这里结果为27岁
select year(now())-left(csny,4),csny from t_user_lisk;

-- rand()函数
在0~1之前获取一个随机数,这样可以通过rand()*3600获取0~1小时内秒数。
用于产生一个范围内的随机数,好用

-- 统计所有数据库大小
select table_schema, sum(data_length+index_length)/1024/1024 as total_mb, sum(data_length)/1024/1024 as data_mb, sum(index_length)/1024/1024 as index_mb, count( *) as tables, curdate() as today from information_schema.tables group by table_schema order by 2 desc;

-- 处理metadata lock
select concat('kill ',id) ,id, db, user, host, command, time, state, info
from information_schema.processlist
order by command

查询进程,出现lock的可以kill id
show full processlist

-- 查看在锁的事务
SELECT * FROM INFORMATION_SCHEMA.INNODB_TRX;

-- 重新加载日志
/usr/local/mysql/bin/mysqladmin -uroot -p flush-log
登录mysql在命令窗口执行flush logs

猜你喜欢

转载自www.cnblogs.com/kaycici/p/13366626.html