# mysql 命令常用参数

参数 含义
-u, --user= 用户名
-p, --password= 密码
-P, --port= 端口号
-h, --host= 服务器名称
-D, --database= 打开指定数据库
–delimiter= 指定分隔符
–prompt= 设置提示符
-V,–version 输出版本信息并退出(必须是大写 V)

登陆 mysql

1
2
3
4
5
6
--one
mysql -uroot -proot -P3306 -h127.0.0.1

--two
mysql -uroot -p -P3306 -h127.0.0.1
Enter password: ****

# 常用命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
-- 显示当前服务器版本
SELECT VERSION(); / mysql --version

-- 显示当前日期时间
SELECT NOW();

-- 显示当前用户
SELECT USER();

-- 当前数据库
SELECT DATABASE();

-- 查看其它数据库中的表
SHOW TABLES FROM <databasename>;

-- 查看表结构
SHOW COLUMNS FROM <tablename>; / desc <tablename>;

SHOW WARNINGS;

mysql> create table products(price decimal(5,2));
Query OK, 0 rows affected (0.71 sec)

mysql> insert into products (price) values (5.026);
Query OK, 1 row affected, 1 warning (0.07 sec)

mysql> show warnings;
+-------+------+--------------------------------------------+
| Level | Code | Message |
+-------+------+--------------------------------------------+
| Note | 1265 | Data truncated for column 'price' at row 1 |
+-------+------+--------------------------------------------+
1 row in set (0.00 sec)

SHOW CREATE TABLE <tableanme>;

MySQL root@localhost:book_shop> show create table books;
+-------+--------------------------------------------------------+
| Table | Create Table |
+-------+--------------------------------------------------------+
| books | CREATE TABLE `books` ( |
| | `book_id` int(11) NOT NULL AUTO_INCREMENT, |
| | `title` varchar(100) DEFAULT NULL, |
| | `author_fname` varchar(100) DEFAULT NULL, |
| | `author_lname` varchar(100) DEFAULT NULL, |
| | `released_year` int(11) DEFAULT NULL, |
| | `stock_quantity` int(11) DEFAULT NULL, |
| | `pages` int(11) DEFAULT NULL, |
| | PRIMARY KEY (`book_id`) |
| | ) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 |
+-------+--------------------------------------------------------+

1 row in set
Time: 0.014s

MySQL root@localhost:book_shop> show create table books \G;
***************************[ 1. row ]***************************
Table | books
Create Table | CREATE TABLE `books` (
`book_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) DEFAULT NULL,
`author_fname` varchar(100) DEFAULT NULL,
`author_lname` varchar(100) DEFAULT NULL,
`released_year` int(11) DEFAULT NULL,
`stock_quantity` int(11) DEFAULT NULL,
`pages` int(11) DEFAULT NULL,
PRIMARY KEY (`book_id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8

1 row in set
Time: 0.001s

# 创建数据库

{} 是必选项,[] 是可选项,| 是做选择项

1
2
3
4
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
[DEFAULT] CHARACTER SET [=] charset_name

CREATE DATABASE mysql-learn;

# 修改数据库

修改数据库的语法结构:

1
2
ALTER {DATABASE | SCHEMA}  [db_name]
[DEFAULT] CHARACTER SET [=] charset_name

比如将刚刚创建的 mysql-learn 的编码方式修改为 utf8

1
ALTER DATABASE people CHARACTER SET utf8;

# 创建数据表

1
2
3
CREATE TABLE [IF NOT EXISTS] table_name (
column_name data_type
)
1
2
3
4
5
CREATE TABLE people(
name VARCHAR(20),
age TINYINT UNSIGNED,
salary FLOAT(8,2) UNSIGNED
);

# 主外键约束

1
2
3
4
5
6
7
8
9
10
11
CREATE TABLE card(
id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
card_no VARCHAR(20) NOT NULL
);

CREATE TABLE people(
id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(10) NOT NULL,
cid SMALLINT UNSIGNED,
FOREIGN KEY(cid) REFERENCES idcard(id) ON DELETE CASCADE
);

Two different methods of writing.

1
2
3
4
5
6
7
8
9
10
11
create table cats(
id int primary key,
name varchar(100),
age int);

create table cats(
id int,
name varchar(100),
age int,
primary key(id)
);

# 自定义函数

创建不带参数的自定义函数

1
SELECT DATE_FORMAT(NOW(), '%Y 年%m 月%d 日 %H 点%i 分%s 秒');
1
2
3
4
5
6
+-------------------------------------------------------+
| DATE_FORMAT(NOW(), '%Y 年%m 月%d 日 %H 点%i 分%s 秒') |
+-------------------------------------------------------+
| 2019 年11 月08 日 16 点20 分59 秒 |
+-------------------------------------------------------+
1 row in set (0.00 sec)
1
2
3
4
CREATE FUNCTION chinese_date() RETURNS VARCHAR(30)
RETURN DATE_FORMAT(NOW(),'%Y 年%m 月%d 日 %H 点%i 分%s 秒');

SELECT chinese_date();

mysql8.0 出现如下错误
ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)

1
2
3
SHOW variables like 'log_bin_trust_function_creators';
--如果为 OFF, 开启 log_bin_trust_function_creators
SET GLOBAL log_bin_trust_function_creators = 1;

带有参数的自定义函数

1
2
3
CREATE FUNCTION avg (num1 SMALLINT UNSIGNED,num2 SMALLINT UNSIGNED)
RETURNS FLOAT(10,2) UNSIGNED
RETURN (num1 + num2) / 2;

具有复合结构函数体的自定义函数

首先需要修改 DELIMITER DELIMITER // , 因为 mysql 默认使用 ; 作为语句的结束

1
2
3
4
5
6
7
CREATE FUNCTION adduser(name VARCHAR(20))
RETURNS INT UNSIGNED
BEGIN
INSERT people(name) VALUES (name);
RETURN LAST_INSERT_ID();
END
//

# 存储过程

不带参数的存储过程

1
2
CREATE PROCEDURE v() SELECT VERSION();
call v();

带有 IN 和 OUT 类型参数的存储过程

1
2
3
4
5
6
7
8
9
CREATE PROCEDURE remove1(IN p_id INT UNSIGNED, OUT user_counts INT UNSIGNED)
BEGIN
DELETE FROM users WHERE id = p_id;
SELECT COUNT(id) FROM users INTO user_counts;
END
//

CALL remove1(44,@counts)
SELECT @counts;

带有多个 OUT 类型参数的存储过程

1
2
3
4
5
6
7
8
CREATE PROCEDURE remove2(IN p_age SMALLINT UNSIGNED,OUT delete_counts SMALLINT UNSIGNED, OUT user_counts SMALLINT UNSIGNED)
BEGIN
DELETE FROM users WHERE age = p_age;
SELECT ROW_COUNT() INTO delete_counts;
SELECT COUNT(id) FROM users INTO user_counts;
END
//
CALL remove2(21, @a, @b);

# information_schema

mysql 的 information_schema.tablesinformation_schema.columns 分別保存着表和栏位的相关信息。

1
2
3
4
5
SELECT  b.table_name, b.table_comment, a.column_name, a.column_type,a.column_comment
FROM information_schema.columns a
JOIN information_schema.tables b
ON a.table_schema =b.table_schema AND a.table_name =b.table_name
WHERE a.table_name='pets';

# dual

1
2
3
4
SELECT 1 + 1 FROM DUAL;
SELECT 1 + 1;
-- FROM DUAL could be used when you only SELECT computed values, but require a WHERE clause, perhaps to test that a script correctly handles empty resultsets:
SELECT 1 FROM DUAL WHERE FALSE;

# variables

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
--查询变量设置
show variables like '%connect_timeout%'; --默认 session 变量
show local variables like '%connect_timeout%';
show session variables like '%connect_timeout%';
show global variables like '%connect_timeout%';

--全局变量设置
SET GLOBAL log_bin_trust_function_creators=1;
SET @@global.log_bin_trust_function_creators=1;
--sesseion 变量设置
SET log_bin_trust_function_creators=1; --默认 session 变量
SET SESSION log_bin_trust_function_creators=1;
SET @@session.log_bin_trust_function_creators=1;

--自定义变量
set @test="test";
select @test;

# 批量插入

1
insert into some_table (col1, col2) values (val1, val2), (val3, val4), (val5, val6)

# +

mysql 中的 + 只有作为运算符,没有作为连接符的功能,连接字符使用 concat 。+ 运算如果是字符型,会试图将字符转换为数字,转换成功做加法运算,转换失败将字符转换为 0 做加法运算

1
2
3
4
5
6
7
select 1 + 1; --2
select '1' + 1; --2
select '1' + '1'; --2
select 'a' + 1; --1
select 'a' + 'a'; --0
select null + 1; -- NULL
select concat(1, 1); --11

# CONCAT With NULL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mysql> select concat('My', NULL, 'SQL');
+---------------------------+
| concat('My', NULL, 'SQL') |
+---------------------------+
| NULL |
+---------------------------+
1 row in set (0.00 sec)

mysql> select concat('My', '', 'SQL');
+-------------------------+
| concat('My', '', 'SQL') |
+-------------------------+
| MySQL |
+-------------------------+
1 row in set (0.00 sec)

# CONCAT_WS Concat With Separator

1
2
3
4
5
6
7
mysql> select concat_ws(',', 'name', 'age', 'height'); 
+-----------------------------------------+
| concat_ws(',', 'name', 'age', 'height') |
+-----------------------------------------+
| name,age,height |
+-----------------------------------------+
1 row in set (0.00 sec)

# LENGTH and CHAR_LENGTH

1
2
3
4
5
6
mysql> select length('你好'),char_length('你好'); 
+----------------+---------------------+
| length('你好') | char_length('你好') |
+----------------+---------------------+
| 4 | 2 |
+----------------+---------------------+

# Date, Time and DateTime

1
2
3
4
5
6
MySQL root@localhost:book_shop> select curdate(), curtime(), now();
+------------+-----------+---------------------+
| curdate() | curtime() | now() |
+------------+-----------+---------------------+
| 2024-04-19 | 16:30:51 | 2024-04-19 16:30:51 |

# Unsigned Int

1
2
3
4
5
6
7
MySQL root@localhost:book_shop>  CREATE TABLE `parent` (
-> `children` tinyint(3) unsigned DEFAULT NULL
-> );
Query OK, 0 rows affected
Time: 0.484s
MySQL root@localhost:book_shop> insert into parent values (-3);
(1264, "Out of range value for column 'children' at row 1")

In Oracle

1
2
3
4
5
6
create table parent (
children number,
constraint parent_unsigend_tinyint check (children between 0 and 255)
);

insert into parent values (-3); --ORA-02290: check constraint (APPS.PARENT_UNSIGEND_TINYINT) violated

# <=>

<=> 安全等于可以用来判断是否等于 null.

1
2
3
select * from employees where commission_pct is null; 
select * from employees where commission_pct <=> null;
select * from employees where commission_pct <=> 100;

# like null

select * from employeesselect * from employees where commission_pct like '%%' and last_name like '%%' 结果是否一样?

不一定,因为 commission_pct 和 last_name 中可能存在 null

# mod or %

mod or % 取余数 mod(a, b) ⇒ a - a / b * b 其中 a / b 是取整运算 10 / 3 = 3

1
select mod(10, 3), mod(10, -3), -10 % -3, -10 % 3; --1, 1, -1, -1

# 逻辑运算符 xor

mysql 可以使用逻辑运算符 xor

1
2
3
4
5
6
7
8
9
10
11
12
13
mysql> select 1 from dual where 1=1 xor 1=0;
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.01 sec)

mysql> select 1 from dual where 1=1 xor 1=1;
Empty set (0.00 sec)

mysql> select 1 from dual where 0=0 xor 0=0;
Empty set (0.00 sec)

位运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
mysql> select 1&0;
+-----+
| 1&0 |
+-----+
| 0 |
+-----+
1 row in set (0.00 sec)

mysql> select 1|0;
+-----+
| 1|0 |
+-----+
| 1 |
+-----+
1 row in set (0.00 sec)

mysql> select ~1;
+----------------------+
| ~1 |
+----------------------+
| 18446744073709551614 |
+----------------------+
1 row in set (0.00 sec)

mysql> select 1^0;
+-----+
| 1^0 |
+-----+
| 1 |
+-----+
1 row in set (0.01 sec)

mysql> select 1>>1;
+------+
| 1>>1 |
+------+
| 0 |
+------+
1 row in set (0.00 sec)

mysql> select 1<<1;
+------+
| 1<<1 |
+------+
| 2 |
+------+
1 row in set (0.00 sec)

# GROUP_CONCAT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
CREATE TEMPORARY TABLE emp(
empno varchar(10),
ename varchar(100),
deptno varchar(10)
);

insert into emp values ('10', 'Babb', '10');
insert into emp values ('20', 'Julian', '10');
insert into emp values ('30', 'Owen', '10');
insert into emp values ('40', 'Yoyo', '20');
insert into emp values ('50', 'Sunny', '20');

select deptno, group_concat(ename), count(*)
from emp
group by deptno;

+--------+---------------------+----------+
| deptno | group_concat(ename) | count(*) |
+--------+---------------------+----------+
| 10 | Babb,Julian,Owen | 3 |
| 20 | Yoyo,Sunny | 2 |
+--------+---------------------+----------+
2 rows in set (0.00 sec)

# CTE Common Table Expression

CTE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
WITH cte (col1, col2) AS
(
SELECT 1, 2
UNION ALL
SELECT 3, 4
)
SELECT col1, col2 FROM cte;


with cte as
(
select 1 as col1, 2 as col2
union all
select 3, 4
)
select col1, col2 from cte;

with cte1 as (select 1)
select * from (with cte2 as (select 2) select * from cte2 join cte1) as dt;


with recursive cte(n) as
(
select 1
union all
select n + 1 from cte where n < 5
)
select * from cte;

-- Error Code: 1406. Data too long for column 'str' at row 1
with recursive cte as
(
select 1 as n, 'abc' as str
union all
select n + 1, concat(str, str) from cte where n < 3
)
select * from cte;


with recursive cte as
(
select 1 as n, cast('abc' as char(20)) str
union all
select n + 1, concat(str, str) from cte where n < 3
)
select * from cte;


with recursive fibonacci(n, fib_n, next_fib_n) as
(
select 1, 0, 1
union all
select n + 1, next_fib_n, fib_n + next_fib_n from fibonacci where n < 10
)
select * from fibonacci where n = 8;



with recursive dates (date) as
(
select sysdate()
union all
select date + interval 1 day from dates
where date <= sysdate() + interval 10 day

)
select * from dates;


use test;
CREATE TABLE employees (
id INT PRIMARY KEY NOT NULL,
name VARCHAR(100) NOT NULL,
manager_id INT NULL,
INDEX (manager_id),
FOREIGN KEY (manager_id) REFERENCES employees (id)
);
INSERT INTO employees VALUES
(333, "Yasmina", NULL), # Yasmina is the CEO (manager_id is NULL)
(198, "John", 333), # John has ID 198 and reports to 333 (Yasmina)
(692, "Tarek", 333),
(29, "Pedro", 198),
(4610, "Sarah", 29),
(72, "Pierre", 29),
(123, "Adil", 692);

select * from employees;

with recursive employee_paths (id, name, path) as
(
select id, name, cast(id as char(200))
from employees
where manager_id is null
union all
select e.id, e.name, concat(ep.path, ',', e.id)
from employee_paths as ep join employees as e
on ep.id = e.manager_id
)
select * from employee_paths order by path;

# Load SQL Script

cats.sql

cats.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
create table cats(
id int primary key auto_increment,
name varchar(100),
age int
);

insert into
cats (name, age)
values
('Kitty', 3);

insert into
cats (name, age)
values
('Tom', 3);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$ mysql -uroot -p
Enter password: ****
...

mysql> use test;
Database changed
mysql> drop table cats;
Query OK, 0 rows affected (0.94 sec)

mysql> source cats.sql
Query OK, 0 rows affected (1.17 sec)

Query OK, 1 row affected (0.08 sec)

Query OK, 1 row affected (0.22 sec)

mysql> select * from cats;
+----+-------+------+
| id | name | age |
+----+-------+------+
| 1 | Kitty | 3 |
| 2 | Tom | 3 |
+----+-------+------+
2 rows in set (0.00 sec)

# mycli

mycli 是一个 mysql 命令行提示工具,安装完成后使用和 mysql 一致,例如登陆 mysql ,

1
pip install mycli
Edited on