Comprobación rápida de MySQL
Debido a que a menudo olvido algunas declaraciones, palabras clave, operaciones, etc. de MySQL en mi trabajo y estudio diario, recientemente me tomé un tiempo para escribir el siguiente contenido sobre MySQL. es como un diccionario
Restablecer contraseña de MySQL Operador
de tipo de datos Funciones comunes Operaciones básicas de la base de datos de integridad de datos Este artículo opera con datos en la tabla Subconsulta Conexión de múltiples tablas Vista de índice Preprocesamiento de declaraciones SQL Funciones personalizadas y procedimientos almacenados Programación en MySQL
Operaciones sobre la propia mesa.
Ver tabla
ver todo
1 show tables;
2 SHOW TABLE STATUS
[{
FROM | IN} 数据库名]
[LIKE 'pattern' | WHERE where筛选表达式]
show table status类似show tables,但会显示更多信息
mysql> show table status from sys;
+-----------------------------------------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |
+-----------------------------------------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+
| host_summary | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 2021-03-08 19:30:21 | NULL | NULL | NULL | NULL | NULL | VIEW |
| host_summary_by_file_io | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 2021-03-08 19:30:21 | NULL | NULL | NULL | NULL | NULL | VIEW |
...
# 使用show tables时
mysql> use sys;
mysql> show tables;
+-----------------------------------------------+
| Tables_in_sys |
+-----------------------------------------------+
| host_summary |
| host_summary_by_file_io |
| host_summary_by_file_io_type |
...
Ver estructura de la tabla
1 describe tb_name;
desc是describe的缩写
# 查看表结构详细信息
2 show create table 表名;
mysql> use sys;
mysql> desc host_summary;
+------------------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------------+---------------+------+-----+---------+-------+
| host | varchar(255) | YES | | NULL | |
...
mysql> show create table host_summary;
+--------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
| View | Create View | character_set_client | collation_connection |
+--------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
| host_summary | CREATE ALGORITHM=TEMPTABLE DEFINER=`mysql.sys`@`localhost` SQL SECURITY INVOKER VIEW `host_summary` (`host`,`statements`,`statement_latency`,`statement_avg_latency`,`table_scans`,`file_ios`,`file_io_latency`,`current_connections`,`total_connections`,`unique_users`,`current_memory`,`total_memory_allocated`) AS select if((`performance_schema`.`accounts`.`HOST` is null),'background',`performance_schema`.`accounts`.`HOST`) AS `host`,sum(`stmt`.`total`) AS `statements`,format_pico_time(sum(`stmt`.`total_latency`)) AS `statement_latency`,format_pico_time(ifnull((sum(`stmt`.`total_latency`) / nullif(sum(`stmt`.`total`),0)),0)) AS `statement_avg_latency`,sum(`stmt`.`full_scans`) AS `table_scans`,sum(`io`.`ios`) AS `file_ios`,format_pico_time(sum(`io`.`io_latency`)) AS `file_io_latency`,sum(`performance_schema`.`accounts`.`CURRENT_CONNECTIONS`) AS `current_connections`,sum(`performance_schema`.`accounts`.`TOTAL_CONNECTIONS`) AS `total_connections`,count(distinct `performance_schema`.`accounts`.`USER`) AS `unique_users`,format_bytes(sum(`mem`.`current_allocated`)) AS `current_memory`,format_bytes(sum(`mem`.`total_allocated`)) AS `total_memory_allocated` from (((`performance_schema`.`accounts` join `x$host_summary_by_statement_latency` `stmt` on((`performance_schema`.`accounts`.`HOST` = `stmt`.`host`))) join `x$host_summary_by_file_io` `io` on((`performance_schema`.`accounts`.`HOST` = `io`.`host`))) join `x$memory_by_host_by_current_bytes` `mem` on((`performance_schema`.`accounts`.`HOST` = `mem`.`host`))) group by if((`performance_schema`.`accounts`.`HOST` is null),'background',`performance_schema`.`accounts`.`HOST`) | utf8mb4 | utf8mb4_0900_ai_ci |
+--------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
1 row in set (0.01 sec)
Agregar tabla
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] 表名
(字段名 数据类型 [完整性约束],...)
如果指定temporary,则创建的是临时表,
会话结束会自动释放,并且show tables看不到该表
mysql> use test;
Database changed
mysql> show tables;
Empty set (0.00 sec)
mysql> create table t1(id int primary key, name char(10));
Query OK, 0 rows affected (0.12 sec)
mysql> desc t1;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Eliminar tabla
DROP [TEMPORARY] TABLE [IF EXISTS]
表名1 [, 表名2] ...
[RESTRICT | CASCADE]
Las palabras clave RESTRICT y CASCADE no tienen ningún efecto. Estas dos palabras clave se utilizan para facilitar la portabilidad desde otras bases de datos.
Eliminar una tabla también eliminará los datos de la tabla.
drop table t1; # 删除t1表
Modificar tabla
Modificar campos en la tabla
ALTER TABLE 表名
[alter_option [, alter_option] ...]
[partition_options]
alter_option: alter操作,如增加、删除、修改等,下面详细介绍。
partition_options: 分区操作
Agregue campo
ALTER TABLE 表名
ADD [COLUMN] 要增加的字段名 数据类型 完整性约束
[FIRST | AFTER 表中存在的字段名]
# 例如
alter table t1
add column sex char(1) not null default '女'
after name;
primero y después especifique la posición del nuevo campo. Si no se escribe, se agregará al final de forma predeterminada. (Nota: no agregue ningún carácter después del primero)
También puede agregar varios campos al mismo tiempo
ALTER TABLE 表名
ADD [COLUMN] 要增加的字段名 数据类型 完整性约束[,...]
# 例如
alter table t1
add sex char(1) default '男',
age int;
Agregar/eliminar restricciones de integridad para los campos de la tabla
ALTER TABLE 表名
# 添加主键
ADD PRIMARY KEY(字段名,...)
# 为字段指定唯一约束
| ADD UNIQUE (字段名,...)
# 添加外键
| ADD FOREIGN KEY(字段名,...)
references 另一个表名(字段名,...)
# 为字段增加check约束
| ADD CHECK (expr)
# 为字段删除check
| DROP CHECK symbol
# 去除字段主键约束
| DROP PRIMARY KEY
# 去除字段外键约束
| DROP FOREIGN KEY fk_symbol
Modificar campos
cambiarModificar campo
ALTER TABLE 表名
CHANGE [COLUMN] 旧字段名 新字段名 数据类型 完整性约束
[FIRST | AFTER 表中字段名]
mysql> desc t1;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> desc t1;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.01 sec)
mysql> alter table t1
-> change name xingming varchar(12) not null
-> first; # 将name改成xingming并放在首位
Query OK, 0 rows affected (0.26 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc t1;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| xingming | varchar(12) | NO | | NULL | |
| id | int | NO | PRI | NULL | |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
modificar modificar campo
ALTER TABLE 表名
MODIFY [COLUMN]
字段名 新数据类型 [新完整性约束]
[FIRST | AFTER 字段名]
alter table t1
modify column
xingming char(10) unique
after id;
mysql> alter table t1
-> modify column
-> xingming char(10) unique
-> after id;
Query OK, 0 rows affected (0.21 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc t1;
+----------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| xingming | char(10) | YES | UNI | NULL | |
+----------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)
renombrarRenombrar campo
ALTER TABLE 表名
RENAME COLUMN 旧字段名 TO 新字段名
mysql> alter table t1 rename column xingming to name;
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc t1;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| name | char(10) | YES | UNI | NULL | |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Eliminar campo
ALTER TABLE 表名 DROP [COLUMN] 字段名
alter table t1 drop name;
Modificar el nombre de la tabla
ALTER TABLE 表名 RENAME [TO | AS] 新表名
mysql> alter table t1 rename to t2;
Query OK, 0 rows affected (0.02 sec)
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| t2 |
+----------------+
1 row in set (0.00 sec)
mysql> alter table t2 rename as t1;
Query OK, 0 rows affected (0.02 sec)
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| t1 |
+----------------+
1 row in set (0.00 sec)