Can't remember the fragmented MySQL foundation? See how this article saves you

Preface

In daily development, some infrequent and relatively basic knowledge is always easy to forget or become a little ambiguous after a period of time. This article mainly records some basic knowledge about MySQL database for quick review in the future.

SQL commands

SQL commands can be divided into four groups: DDL , DML , DCL and TCL . The commands included in the four groups are as follows

DDL

DDL is the abbreviation of Data Definition Language, which deals with database schemes and describes how data should reside in the database.

CREATE: Create a database and its objects (such as tables, indexes, views, stored procedures, functions, and triggers) ALTER: Change the structure of an existing database DROP: Delete objects from the database TRUNCATE: Delete all records from the table, including records All allocated space will be deleted COMMENT: add comment RENAME: rename object

Common commands are as follows:

# 建表
CREATE TABLE sicimike  (
  id int(4) primary key auto_increment COMMENT '主键ID',
  name varchar(10) unique,
  age int(3) default 0,
  identity_card varchar(18)
  # PRIMARY KEY (id) // 也可以通过这种方式设置主键
  # UNIQUE KEY (name) // 也可以通过这种方式设置唯一键
  # key/index (identity_card, col1...) // 也可以通过这种方式创建索引
) ENGINE = InnoDB;

# 设置主键
alter table sicimike add primary key(id);

# 删除主键
alter table sicimike drop primary key;

# 设置唯一键
alter table sicimike add unique key(column_name);

# 删除唯一键
alter table sicimike drop index column_name;

# 创建索引
alter table sicimike add [unique/fulltext/spatial] index/key index_name (identity_card[(len)] [asc/desc])[using btree/hash]
create [unique/fulltext/spatial] index index_name on sicimike(identity_card[(len)] [asc/desc])[using btree/hash]
example: alter table sicimike add index idx_na(name, age);

# 删除索引
alter table sicimike drop key/index identity_card;
drop index index_name on sicimike;

# 查看索引
show index from sicimike;

# 查看列
desc sicimike;

# 新增列
alter table sicimike add column column_name varchar(30);

# 删除列
alter table sicimike drop column column_name;

# 修改列名
alter table sicimike change column_name new_name varchar(30);

# 修改列属性
alter table sicimike modify column_name varchar(22);

# 查看建表信息
show create table sicimike;

# 添加表注释
alter table sicimike comment '表注释';

# 添加字段注释
alter table sicimike modify column column_name varchar(10) comment '姓名';
————————————————
版权声明:本文为CSDN博主「Sicimike」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Baisitao_/article/details/104714764

DML

DML is a data manipulation language abbreviation (Data Manipulation Language), including the most common SQL statements, such as SELECT, INSERT, UPDATE, DELETEetc., which is used to store , modify , retrieve and delete data in the database.

  • Pagination

    -- 查询从第11条数据开始的连续5条数据
    select * from sicimike limit 10, 5
  • group by

    By default, the group by statement in MySQL does not require the column returned by select to be a grouped column or an aggregate function. If the column of the select query is not a grouped column or an aggregate function, the data of the first record in the group will be returned. Compare the following two SQL statements. In the second SQL statement, cname is neither a grouping column nor an aggregate function. So in the liming group, cname takes the first piece of data.

    mysql> select * from c;
    +-----+-------+----------+
    | CNO | CNAME | CTEACHER |
    +-----+-------+----------+
    |   1 | 数学  | liming   |
    |   2 | 语文  | liming   |
    |   3 | 历史  | xueyou   |
    |   4 | 物理  | guorong  |
    |   5 | 化学  | liming   |
    +-----+-------+----------+
    5 rows in set (0.00 sec)
    
    mysql> select cteacher, count(cteacher), cname from c group by cteacher;
    +----------+-----------------+-------+
    | cteacher | count(cteacher) | cname |
    +----------+-----------------+-------+
    | guorong  |               1 | 物理  |
    | liming   |               3 | 数学  |
    | xueyou   |               1 | 历史  |
    +----------+-----------------+-------+
    3 rows in set (0.00 sec)
    ————————————————
  • The having keyword is used to filter the grouped data, and the function is equivalent to where before the grouping, but the requirements are more stringent. The filter condition is either an aggregate function (... having count(x)> 1), or the column that appears after select (select col1, col2 ... group by x having col1> 1)

  • Multi-table update

    - update tableA a inner join tableB b on a.xxx = b.xxx set a.col1 = xxx, b.col1 = xxx where ...
    
  • Multi-table delete

    - delete a, b from tableA a inner join tableB b on a.xxx = b.xxx where a.col1 = xxx and b.col1 = xxx 
    

DCL

DCL is a data control language abbreviation (Data Control Language), which contains information such as GRANTthe command and the like, and is mainly related to the database system privileges, permissions, and other controls.

  • GRANT :Permission to allow users to access the database

  • REVOKE: Revoke the user's access authority granted by the GRANT command

TCL

TCL is a transaction control language abbreviation (Transaction Control Language) for database transaction processing

  • COMMIT: Commit the transaction
  • ROLLBACK: Roll back the transaction in case of any error

Paradigm

Database standardization, also known as regularization and standardization, is a series of principles and techniques for database design to reduce data redundancy in the database and improve data consistency. Edgar Cod, the inventor of the relational model, first proposed this concept and defined the concepts of first normal form, second normal form and third normal form in the early 1970s, and jointly defined it with Raymond F. Boyce in 1974 The improved paradigm of the third paradigm-BC paradigm. The exceptions include the fourth paradigm for multi-value dependence, the fifth paradigm, DK paradigm, and the sixth paradigm for connection dependence.

Now the database design satisfies 3NF at most . It is generally believed that the paradigm is too high. Although it has better constraints on the data relationship, it also leads to the increase of the data relationship table and makes the database IO more busy. The relationship constraints that were originally handled by the database are now more Completed in the database using the program.

First normal form

Definition: All fields (columns) in the database are single attributes and cannot be divided . This single attribute is composed of basic data types, such as integer, floating point, string, etc. The first normal form is to ensure the atomicity of the column.

The above table does not meet the first normal form. The address column can be divided into provinces, cities, districts, etc.

Second normal form

Definition: a database table does not exist for any non-key fields of the key field partial function dependent part functional dependency means that there is a combination of keywords case of a non-keyword decision key second paradigm is satisfied On the basis of the first paradigm, eliminate the partial dependence of non-primary key columns on the combined primary key

In the above table, if you want to set the primary key, you can only combine the product name and the supplier name to form a joint primary key. But the price and the classification depends only on the product name , vendor phone only rely on vendor name , so the above table does not meet the second paradigm, can be changed to the following form: product information table

Supplier Information Form

Commodity-supplier association table

Third normal form

Definition: All non-primary key attributes are only related to candidate keys, that is to say, non-primary key attributes should be independent and unrelated. The third normal form is to eliminate the transitive dependence between columns on the basis of satisfying the second normal form .

In the above table, the classification description of the product depends on the classification , and the classification depends on the product name , rather than the classification description directly relying on the product name . This forms a transitive dependency , so it does not conform to the third normal form. Can be changed to the following form

Commodity table

Commodity classification table

In database design, following paradigm and anti-paradigm has always been a controversial issue. Following the paradigm has better constraints on data relationships and reduces data redundancy, which can better ensure data consistency. The anti-paradigm is for better performance. Therefore, there is no clear standard for paradigm or anti-paradigm, and the one that suits your business scenario is the best.

In anti-paradigm design, the following issues need to be considered, namely insert exception, update exception and delete exception

  • Insertion exception: If an entity exists with the existence of another entity, that is, the lack of an entity is unable to represent this entity, then there is an insertion exception for this table.
  • Update exception: If you need to update multiple rows when changing a single attribute of an entity instance corresponding to the table, it means that the table has an update exception
  • Delete exception: If you delete a row of the table to indicate that an entity instance fails, causing the loss of another entity instance information, then this table has a delete exception

Take a table that violates the second normal form as an example

If the supplier of Coke Second Manufacturing Plant has not yet started to supply, there is no second record in the table, and the supplier’s phone number cannot be recorded, so there will be an insertion exception; if the price of Coke needs to be increased, the table needs to be updated. If you delete the supply information of the second manufacturing plant of Coke, then the phone of the supplier is also lost, so there is an abnormal deletion.

Generally, there will be abnormal update and delete abnormal tables.

Horizontal table and vertical table

SQL script

# 横表
CREATE TABLE `table_h2z` (
`name` varchar(32) DEFAULT NULL,
`chinese` int(11) DEFAULT NULL,
`math` int(11) DEFAULT NULL,
`english` int(11) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*Data for the table `table_h2z` */
insert  into `table_h2z`(`name`,`chinese`,`math`,`english`) values 
('mike',45,43,87),
('lily',53,64,88),
('lucy',57,75,75);

# 纵表
CREATE TABLE `table_z2h` (
  `name` varchar(32) DEFAULT NULL,
  `subject` varchar(8) NOT NULL DEFAULT '',
  `score` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `table_z2h` */
insert  into `table_z2h`(`name`,`subject`,`score`) values 
('mike','chinese',45),
('lily','chinese',53),
('lucy','chinese',57),
('mike','math',43),
('lily','math',64),
('lucy','math',75),
('mike','english',87),
('lily','english',88),
('lucy','english',75);

Horizontal table to vertical table

SELECT NAME, 'chinese' AS `subject`,  chinese AS `score` FROM table_h2z
UNION ALL
SELECT NAME, 'math' AS `subject`,  math AS `score` FROM table_h2z
UNION ALL
SELECT NAME, 'english' AS `subject`, english AS `score` FROM table_h2z

Results of the

+------+---------+-------+
| name | subject | score |
+------+---------+-------+
| mike | chinese |    45 |
| lily | chinese |    53 |
| lucy | chinese |    57 |
| mike | math    |    43 |
| lily | math    |    64 |
| lucy | math    |    75 |
| mike | english |    87 |
| lily | english |    88 |
| lucy | english |    75 |
+------+---------+-------+
9 rows in set (0.00 sec)

Vertical to Horizontal Table

SELECT NAME,
    SUM(CASE `subject` WHEN 'chinese' THEN score ELSE 0 END) AS chinese,
    SUM(CASE `subject` WHEN 'math' THEN score ELSE 0 END) AS math,
    SUM(CASE `subject` WHEN 'english' THEN score ELSE 0 END) AS english
FROM table_z2h
GROUP BY NAME

Results of the

+------+---------+------+---------+
| name | chinese | math | english |
+------+---------+------+---------+
| lily |      53 |   64 |      88 |
| lucy |      57 |   75 |      75 |
| mike |      45 |   43 |      87 |
+------+---------+------+---------+
3 rows in set (0.00 sec)

reference

Author: Sicimike

Source: https://blog.csdn.net/Baisitao_/article/details/104714764

Guess you like

Origin blog.csdn.net/qq_17231297/article/details/115370486