MySQL Quick Query-Operations on the table itself

MySQL quick check

Because I often forget some mysql statements, keywords, operations, etc. in my daily work and study, I recently took some time to write the following content about mysql. It's like a dictionary


Reset mysql password
Data type
operator
Common functions Basic operations of
data integrity
database
This article operates
on data in the table
Subquery
Multi-table connection
Index
view
Preprocessing SQL statements
Custom functions and stored procedures
Programming in MySQL


View table

view all

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                  |
...

More

View table structure

1 describe tb_name;
descdescribe的缩写

# 查看表结构详细信息
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)

Add table

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)

More

Delete table

DROP [TEMPORARY] TABLE [IF EXISTS]
    表名1 [, 表名2] ...
    [RESTRICT | CASCADE]

The RESTRICT and CASCADE keywords have no effect. These two keywords are used to facilitate portability from other databases.
Deleting a table will also delete the data in the table.

drop table t1; # 删除t1表

More

Modify table

Modify fields in table

ALTER TABLE 表名
    [alter_option [, alter_option] ...]
    [partition_options]
alter_option: alter操作,如增加、删除、修改等,下面详细介绍。
partition_options: 分区操作

Add field

ALTER TABLE 表名
	ADD [COLUMN] 要增加的字段名 数据类型 完整性约束
        [FIRST | AFTER 表中存在的字段名]


# 例如
alter table t1
	add column sex char(1) not null default '女'
	after name;

first and after specify the position of the new field. If not written, it will be added at the end by default. (Note: Do not add any characters after first)
You can also add multiple fields at the same time

ALTER TABLE 表名
	ADD [COLUMN] 要增加的字段名 数据类型 完整性约束[,...]

# 例如
alter table t1 
	add sex char(1) default '男', 
		age int;

Add/remove integrity constraints for fields in the table

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

Modify fields

changeModify field
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)
modify modify field
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)
renameRename field
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)

Delete field

ALTER TABLE 表名 DROP [COLUMN] 字段名

alter table t1 drop name;

Modify table name

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)

More

Guess you like

Origin blog.csdn.net/weixin_45345384/article/details/115630272