Refer to https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-20-04
Ubuntu 24.04 as example in Win11 WSL2
examples
shell
sql
shell
1 2 3 4 5 6
# root user
apt update
apt install mysql-server-8.0 -y
systemctl status mysql.service
mysql
1 2 3 4 5 6 7 8 9
# Collect infomation
show databases;
SELECT host, user, plugin FROM mysql.user;
CREATE DATABASE `some-db` CHARACTER SET UTF8;
CREATE USER 'rd'@'%' IDENTIFIED WITH mysql_native_password BY 'your_password';
GRANT ALL PRIVILEGES ON `some-db`.* TO 'rd'@'%';
FLUSH PRIVILEGES;
1 2 3 4 5 6 7 8
# root user
vi /etc/mysql/mysql.conf.d/mysqld.cnf
# ...
# Comment this line
#bind-address = 127.0.0.1
# ...
systemctl restart mysql.service
-- 今天
SELECT * FROM 表名 WHERE TO_DAYS(时间字段名) = TO_DAYS(NOW());
-- 昨天
SELECT * FROM 表名 WHERE TO_DAYS(NOW()) - TO_DAYS(时间字段名) <= 1;
-- 本周
SELECT * FROM 表名 WHERE YEARWEEK(DATE_FORMAT(时间字段名,'%Y-%m-%d')) = YEARWEEK(NOW());
-- 上周
SELECT * FROM 表名 WHERE YEARWEEK(DATE_FORMAT(时间字段名,'%Y-%m-%d')) = YEARWEEK(NOW())-1;
-- 近7天
SELECT * FROM 表名 WHERE DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= DATE(时间字段名);
-- 近30天
SELECT * FROM 表名 WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE(时间字段名);
-- 本月
SELECT * FROM 表名 WHERE DATE_FORMAT(时间字段名,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m');
-- 上月
SELECT * FROM 表名 WHERE PERIOD_DIFF(DATE_FORMAT(NOW(),'%Y%m'),DATE_FORMAT(时间字段名,'%Y%m')) = 1;
SELECT * FROM 表名 WHERE DATE_FORMAT(时间字段名,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m') ;
SELECT * FROM 表名 WHERE WEEKOFYEAR(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) = WEEKOFYEAR(NOW());
SELECT * FROM 表名 WHERE MONTH(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) = MONTH(NOW());
SELECT * FROM 表名 WHERE YEAR(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) = YEAR(NOW()) AND MONTH(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) = MONTH(NOW());
-- 近6个月
SELECT * FROM 表名 WHERE 时间字段名 BETWEEN DATE_SUB(NOW(),INTERVAL 6 MONTH) AND NOW();
-- 本季度
SELECT * FROM 表名 WHERE QUARTER(时间字段名) = QUARTER(NOW());
-- 上季度
SELECT * FROM 表名 WHERE QUARTER(时间字段名) = QUARTER(DATE_SUB(NOW(),INTERVAL 1 QUARTER));
-- 本年
SELECT * FROM 表名 WHERE YEAR(时间字段名)=YEAR(NOW());
-- 去年
SELECT * FROM 表名 WHERE YEAR(时间字段名) = YEAR(DATE_SUB(NOW(),INTERVAL 1 YEAR));
UPDATE
UPDATE
1 2
UPDATE <table_name> SET ...;
[TODO]: To be continued...
DELETE
DELETE
1
DELETE FROM <table_name> WHERE ...;
MERGE
CALL
EXPLAIN PLAN
LOCK TABLE
EXAMPLES
Kill
数据库锁死的问题解决
Kill lock
1 2 3 4 5 6 7 8 9 10 11
select *
from information_schema.PROCESSLIST;
select *
from information_schema.INNODB_TRX;
select A.trx_started, B.*
from information_schema.INNODB_TRX A
left join (select * from information_schema.PROCESSLIST) B on A.trx_mysql_thread_id = B.ID;
kill 12345;
JOIN
TCL
TCL: Transaction Control Language, like COMMIT, ROLLBACK, SAVEPOINT, START TRANSACTION