Mysql: Create and manage tables (comprehensive and detailed explanation)



foreword

This blogger will use CSDN to record the experience and knowledge he has personally gained and learned on the way to study software development. Interested friends can pay attention to the blogger!
Perhaps a person can go fast alone, but a group of people can go farther!

1. Basic knowledge

1. A data storage process

Storing data is the first step in processing data. Only by storing the data correctly can we carry out effective processing and analysis. Otherwise, it can only be a mess with no way to start.

So, how can we store various business-related and complicated data of users in an orderly and efficient manner?
In MySQL, a complete data storage process has a total of 4 steps, namely creating a database, confirming fields, creating a data table, and inserting data.
insert image description here

We have to create a database first, instead of creating a data table directly?

Because from the perspective of the system architecture level, the MySQL database system is the database server, database, data table, and row and column of the data table in order from large to small.

The MySQL database server was previously installed. So, we start by creating the database.

2. Identifier naming rules

  1. The database name and table name cannot exceed 30 characters, and the variable name is limited to 29 characters
  2. Must only contain A–Z, a–z, 0–9, _ a total of 63 characters
  3. Object names such as database names, table names, and field names should not contain spaces
  4. In the same MySQL software, databases cannot have the same name; in the same library, tables cannot have the same name; in the same table, fields cannot have the same name
  5. You must ensure that your fields do not conflict with reserved words, database systems, or common methods. If you insist, enclose the SQL statement with ` (emphasis)
  6. Keep the consistency of field names and types: When naming fields and specifying data types for them, you must ensure consistency. If the data type is an integer in one table, then don’t change it to a character type in another table.

3. Data types in MySQL

Among them, the commonly used types are introduced as follows:
insert image description here

2. Create and manage database

1. Create a database

• Method 1: Create a database

CREATE DATABASE 数据库名; 

• Method 2: Create a database and specify a character set

CREATE DATABASE 数据库名 CHARACTER SET 字符集;

• Method 3: Determine whether the database already exists, and create the database if it does not exist (recommended)

CREATE DATABASE IF NOT EXISTS 数据库名; 

If the related database already exists in MySQL, the create statement is ignored and the database is not created anymore.

Note: DATABASE cannot be renamed. Some visualization tools can be renamed. It is done by building a new library, copying all tables to the new library, and then deleting the old library.

2. Use the database

• View all current databases

SHOW DATABASES; #有一个S,代表多个数据库

• View the databases currently in use

SELECT DATABASE();  #使用的一个 mysql 中的全局函数

• View all tables under the specified library

SHOW TABLES FROM 数据库名;

• View database creation information

SHOW CREATE DATABASE 数据库名;
或者:
SHOW CREATE DATABASE 数据库名\G

• use/switch database

USE 数据库名;

Note: Before operating tables and data, you must first indicate which database you are operating on, otherwise you must add "database name." to all objects.

3. Modify the database

• Change the database character set

ALTER DATABASE 数据库名 CHARACTER SET 字符集;  #比如:gbk、utf8等

4. Delete the database

• Method 1: Delete the specified database

DROP DATABASE 数据库名;

• Method 2: Delete the specified database (recommended)

DROP DATABASE IF EXISTS 数据库名;

3. Create a table

1. Create method 1

  1. You must have:
    • CREATE TABLE permission
    • storage
  2. Grammar format:
CREATE TABLE [IF NOT EXISTS] 表名( 字段1, 数据类型 [约束条件] [默认值], 字段2, 数据类型 [约束条件] [默认值], 字段3, 数据类型 [约束条件] [默认值], …… [表约束条件]);

If the IF NOT EXISTS keyword is added, it means: if the data table to be created does not exist in the current database, the data table will be created; if the data table to be created already exists in the current database, the table creation statement will be ignored and no longer created data sheet.

  1. Must specify:
    • Table Name
    • Column name (or field name), data type, length
  2. Optionally specify:
    • Restrictions
    • Defaults
  3. Create table example 1:
-- 创建表
CREATE TABLE emp ( 
 -- int类型  
 emp_id INT,  
 -- 最多保存20个中英文字符  
 emp_name VARCHAR(20),  
 -- 总位数不超过15位  
 salary DOUBLE,  
 -- 日期类型  
 birthday DATE);
DESC emp;

insert image description here

When MySQL executes the table creation statement, it sets the type of the id field to int (11), where 11 is actually the display width specified by the int type, and the default display width is 11. You can also specify the display width of the data when creating the data table.

  1. Create table example 2:
CREATE TABLE dept(    
	-- int类型,自增 
	deptno INT(2) AUTO_INCREMENT, 
	dname VARCHAR(14), 
	loc VARCHAR(13),    
	-- 主键    
	PRIMARY KEY (deptno)
);
DESCRIBE dept;

insert image description here

In MySQL 8.x, specifying an explicit length for the INT type is no longer recommended, and such syntax may be removed in future versions.

2. Create method 2

• Use the AS subquery option to combine creating tables and inserting data
insert image description here

• There should be one-to-one correspondence between the specified column and the column in the subquery
• Define the column by column name and default value

CREATE TABLE emp1 AS SELECT * FROM employees;
CREATE TABLE emp2 AS SELECT * FROM employees WHERE 1=2; -- 创建的emp2是空表
CREATE TABLE dept80
AS 
SELECT  employee_id, last_name, salary*12 ANNSAL, hire_date
FROM    employees
WHERE   department_id = 80;
DESCRIBE dept80;

3. View the data table structure

After creating a data table in MySQL, you can view the structure of the data table. MySQL supports using DESCRIBE/DESCstatements to view the data table structure, and also supports using SHOW CREATE TABLEstatements to view the data table structure.

The syntax format is as follows:

SHOW CREATE TABLE 表名\G

Using SHOW CREATE TABLEthe statement, you can not only view the detailed statement when the table is created, but also view the storage engine and character encoding.

Four, modify the table

Modifying a table refers to modifying the structure of an existing data table in the database.

Use ALTER TABLEthe statement to:
• add columns to an existing table
• modify columns in an existing table
• drop columns in an existing table
• rename columns in an existing table

1. Add a column

The syntax format is as follows:

ALTER TABLE 表名 ADDCOLUMN】 字段名 字段类型 【FIRST|AFTER 字段名】;

Example:

ALTER TABLE dept80 
ADD job_id varchar(15);

insert image description here

2. Modify a column

• The data type, length, default value and position of the column can be modified
• The syntax for modifying the field data type, length, default value and position is as follows:

ALTER TABLE 表名 MODIFYCOLUMN】 字段名1 字段类型 【DEFAULT 默认值】【FIRST|AFTER 字段名2;

• Example:

ALTER TABLE dept80MODIFY last_name VARCHAR(30);
ALTER TABLE dept80MODIFY salary double(9,2) default 1000;

• Modifications to default values ​​only affect future modifications to the table
• In addition, column constraints can also be modified in this way. Let's not talk about it here.

3. Rename a column

Rename columns using the CHANGE old_column new_column dataType clause. The syntax format is as follows:

ALTER TABLE 表名 CHANGE 【column】 列名 新列名 新数据类型;

Example:

ALTER TABLE  dept80CHANGE department_name dept_name varchar(15); 

4. Delete a column

The syntax for deleting a field in a table is as follows:

ALTER TABLE 表名 DROPCOLUMN】字段名

Example:

ALTER TABLE  dept80
DROP COLUMN  job_id; 

5. Rename table

• Method 1: Use RENAME

RENAME TABLE emp
TO myemp;

• Method 2:

ALTER table dept
RENAME [TO] detail_dept;  -- [TO]可以省略

• Must be the owner of the object

Six, delete the table

• In MySQL, when a data table is not associated with any other data table, the current data table can be deleted directly.
• Both data and structures are deleted
• All running related transactions are committed
• All related indexes are dropped
• Syntax format:

DROP TABLE [IF EXISTS] 数据表1 [, 数据表2,, 数据表n];

IF EXISTSThe meaning of is: if the corresponding data table exists in the current database, delete the data table; if the corresponding data table does not exist in the current database, ignore the delete statement, and no longer execute the operation of deleting the data table.

• Example:

DROP TABLE dept80;

DROP TABLEStatements cannot be rolled back

7. Clear the table

  1. TRUNCATE TABLEstatement:
    • Delete all data in the table
    • Free up table storage space
  2. Example:
TRUNCATE TABLE detail_dept;
  1. TRUNCATEThe statement cannot be rolled back, but using DELETEthe statement to delete data can be rolled back
  2. Compared:
SET autocommit = FALSE;  
DELETE FROM emp2; 
#TRUNCATE TABLE emp2;  
SELECT * FROM emp2;  
ROLLBACK;  
SELECT * FROM emp2;

Alibaba development specification:
[Reference] TRUNCATE TABLE is faster than DELETE, and uses less system and transaction log resources, but TRUNCATE has no transactions and does not trigger TRIGGER, which may cause accidents, so it is not recommended to use this statement in development code.
Description: TRUNCATE TABLE is functionally identical to a DELETE statement without a WHERE clause.

8. The general process of using MySQL

  1. Connect to MySQL server
  2. create database
  3. create table
  4. Define columns and data types
  5. set primary key
  6. add index
  7. modify table structure
  8. delete table

Let's dive into these topics step by step.

1. Connect to the MySQL server

Before you can start creating and managing tables, you first need to connect to a MySQL server. You can use the MySQL command line client or GUI tools such as phpMyAdmin or MySQL Workbench to connect to the server.

2. Create a database

Before creating a table, a database must be created to store the table. A new database can be created with the following command:

CREATE DATABASE database_name;

This will create a new database called database_name on the MySQL server.

3. Create a table

Once you have a database, you can create tables to organize your data. Following is the basic syntax for creating a table:

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
    ...
);

You can define as many columns as you want for a table, and assign an appropriate data type to each column.

4. Define columns and data types

When creating a table, each column must specify a data type. MySQL provides various built-in data types such as integers, characters, dates, etc. Here are some examples of common data types:

Integer type: INT, BIGINT, TINYINT, etc.
String type: VARCHAR, CHAR, TEXT, etc.
Date and time type: DATE, DATETIME, TIMESTAMP, etc.
Select the appropriate data type according to your data requirements.

5. Set the primary key

A primary key is a column that uniquely identifies each row of data in a table. When creating a table, one or more primary key columns can be specified. Here's an example of how to set a primary key:

CREATE TABLE table_name (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    ...
);

In the above example, the id column is designated as the primary key.

6. Add index

Indexes are data structures used to quickly find and sort data. By creating indexes on the columns of the table, query performance can be greatly improved. Indexes can be added when the table is created or later. Here's an example of how to add an index:

CREATE TABLE table_name (
    ...
    INDEX index_name (column1, column2, ...)
);

In the above example, index_name is the name of the index and column1, column2, etc. are the columns to create the index on.

7. Modify the table structure

During the life cycle of a database application, it may be necessary to modify the structure of a table. MySQL provides a variety of commands for modifying the table structure, such as ALTER TABLE, ADD COLUMN, DROP COLUMN, etc. For example, to add a new column to a table, the following command can be used:

ALTER TABLE table_name
ADD COLUMN new_column datatype;

8. Delete table

If a table is no longer needed, it can be dropped from the database with the following command:

DROP TABLE table_name;

Note that executing this command will permanently delete the table and its data.

8. Content Expansion

Expansion 1: MySQL field naming in Alibaba's "Java Development Manual"

  1. [Mandatory] Table names and field names must use lowercase letters or numbers. It is forbidden to appear at the beginning of a number, and only a number appears between two underscores. The modification of the database field name is very expensive, because pre-release cannot be performed, so the field name needs to be carefully considered.

    • Positive example: aliyun_admin, rdc_config, level3_name
    • Counter example: AliyunAdmin, rdcConfig, level_3_name
  2. [Mandatory] Disable reserved words, such as desc, range, match, delayed, etc., please refer to MySQL official reserved words.

  3. [Mandatory] The table must have three fields: id, gmt_create, gmt_modified.

    • Note: The id must be the primary key, the type is BIGINT UNSIGNED, auto-increment for a single table, and the step size is 1. The types of gmt_create and gmt_modified are both DATETIME types, the former means active creation in the present tense, and the latter past participle means passive update
  4. [Recommendation] It is best to name the table following "business name_table function".

    • 正例:alipay_task 、 force_project、 trade_config
  5. [Recommendation] The library name should be as consistent as possible with the application name.

  6. [Reference] Appropriate character storage length not only saves database table space and index storage, but more importantly, improves retrieval speed.

    • Positive example: Unsigned values ​​can avoid mistakenly storing negative numbers and expand the range of representation.

insert image description here

Expansion 2: How to understand that operations such as clearing tables and deleting tables need to be cautious? !

The table deletion operation will delete the definition of the table and the data in the table together, and MySQL will not prompt any confirmation information when performing the deletion operation, so you should be cautious when performing the deletion operation.

Before deleting the table, it is best to back up the data in the table, so that the data can be restored in case of an operation error, so as to avoid irreversible consequences.

Similarly, when using ALTER TABLEthe basic modification operation of the table, you should also ensure that the data is fully backed up before performing the operation process, because the change of the database cannot be undone. If an unnecessary field is added, it can be deleted Delete; similarly, if you delete a required column, all data under this column will be lost.

Expansion 3: New feature of MySQL8 - atomization of DDL

In MySQL 8.0, DDL for InnoDB tables supports transactional integrity, that is, DDL operations either succeed or roll back.

The DDL operation rollback log is written to the data dictionary data dictionary table mysql.innodb_ddl_log (this table is a hidden table and cannot be seen through show tables) for rollback operations. By setting parameters, the DDL operation log can be printed and output to the MySQL error log.

Create the database and data table in MySQL 5.7 and MySQL 8.0 respectively, and the results are as follows:

CREATE DATABASE mytest;

USE mytest;

CREATE TABLE book1(
book_id INT ,
book_name VARCHAR(255)
);
SHOW TABLES;
  1. In MySQL 5.7, the test steps are as follows: delete the data table book1 and data table book2, the results are as follows:
mysql> DROP TABLE book1,book2;
ERROR 1051 (42S02): Unknown table 'mytest.book2'

Query the data table name in the database again, and the results are as follows:

mysql> SHOW TABLES;
Empty set (0.00 sec)

It can be seen from the results that although the deletion operation reports an error, the data table book1 is still deleted.

  1. In MySQL 8.0 version, the test steps are as follows:
    delete the data table book1 and data table book2, the results are as follows:
mysql> DROP TABLE book1,book2;
ERROR 1051 (42S02): Unknown table 'mytest.book2'

Query the data table name in the database again, and the results are as follows:

mysql> show tables;
+------------------+
| Tables_in_mytest |
+------------------+
| book1            |
+------------------+
1 row in set (0.00 sec)

As can be seen from the results, the data table book1 has not been deleted.

Guess you like

Origin blog.csdn.net/weixin_52533007/article/details/131545621