Some basic concepts and usage of SQL

Table of contents

1 The "three paradigms" of relational databases

1.1 First Normal Form (1NF): Fields are "atomic" and cannot be further divided.

1.2 Second Normal Form (2NF): On the basis of 1NF, non-primary key fields are completely dependent on primary key fields.

1.3 Third Normal Form (3NF): On the basis of 2NF, any non-primary key field does not depend on other non-primary fields.

2 How to improve the performance of relational database. ("MySQL Must Know" P227) Back up the database and clear junk data.

3 Must master SQL syntax (DDL, DML, TCL, DCL)

3.1 DDL (Data Definition Language)

3.2 TCL (Transaction Control Language)

                  ​​​​​​​​3.3 DML (Data Manipulation Language)

3.4 DCL (Data Control Language)


1 The "three paradigms" of relational databases

When designing a relational database, you need to comply with different specification requirements according to the situation. These different specification requirements are called different paradigms. The higher the paradigm, the lower the redundancy, but the agent performance pressure may also increase.

There are 6 paradigms for relational databases, but in practice we often require compliance with the first three paradigms: first normal form (1NF), second normal form (2NF), and third normal form (3NF).

1.1 First Normal Form (1NF): Fields are "atomic" and cannot be further divided.

(1) Analysis: Each column of a database table is an indivisible atomic data item, rather than a non-atomic data item such as a collection, an array, or a record. That is, when an attribute in an entity has multiple values, it must be split into different attributes. In relational databases, the first normal form (1NF) is the basic requirement for the design of relational schemas.

(2) Example: In the "Student Name" field, the surname and first name must be taken as a whole, and it is impossible to distinguish which part is the surname and which part is the first name; if you want to distinguish the first and last name, you must design it as two independent fields.

1.2 Second Normal Form (2NF): On the basis of 1NF, non-primary key fields are completely dependent on primary key fields.

(1) Parsing: 2NF requires that each record in the database table must be uniquely distinguishable. Select an attribute or attribute group that can distinguish each entity as the unique identifier of the entity. When no candidate is found, additional attributes can be added to achieve distinction.

2NF requires that the attributes of an entity are completely dependent on the primary key attribute. There cannot be an attribute that only depends on a part of the primary key. If it exists, then this attribute and this part of the primary key attribute should be separated to form a new entity. There is a one-to-many relationship between the new entity and the original entity.

(2) Example: Consider a common "student course selection information form"

Student course selection information form (student number, student name, age, gender, courses, course credits, department, subject grades, department office address, department office phone number)

Problem: The name and age are not dependent on the course, that is, they are not completely dependent on the main attribute, so they do not meet the requirements of the second normal form, which will cause data redundancy: the same course is taken by n students, and the "credits" are repeated n1 times; the same The student has taken m courses, and the name and age are repeated m1 times. Student course selection information form (student number, student name, age, gender, courses, course credits, department, subject grades, department office address, department office phone number)

Solution: Change the "Student Information Form" to the following three forms: 

Student table (student number, name, age, gender, department, department office address, department phone number) Curriculum table (course name, credits) Course selection relationship table (student number, course name, grades)

1.3 Third Normal Form (3NF): On the basis of 2NF, any non-primary key field does not depend on other non-primary fields.

(1) Analysis: The third normal form (3NF) requires that a database table does not contain non-primary key information already contained in other tables.

(2) Example: 

Student form (student number, name, age, gender, department, department office address, department office phone number)

Question: The primary key in the student table is the student number, but the student number, department, address of the department office, and phone number of the department office form a dependency relationship. (Student number) → (Department) → (Department office location, Department office phone number)

Solution: Disassemble the student table into: 

Student table (student number, name, age, gender, department) Department table (department, department office address, department office phone number)

   

2 How to improve the performance of relational database. ("MySQL Must Know" P227) Back up the database and clear junk data.

(1) There are always more than one way to write the same select statement, and you should experiment with joins, unions, subqueries, etc. to find the best way.

(2) Never retrieve more data than needed, don't use select * unless you really need every column.

(3) Create an index, which can avoid full table scans. Create indexes for fields that frequently appear in where and order by clauses. At the same time updating the index is to pay an additional cost, the index is not the better.

(4) Complex or conditions can be realized by combining multiple select statements with union, which will greatly improve performance.

(5) Like fuzzy query is very slow, use full-text index instead of like.

(6) Use stored procedures or precompiled SQL statements to improve the execution efficiency of multiple statements.

(7) Back up the database frequently and remove junk data. 

3 Must master SQL syntax (DDL, DML, TCL, DCL)

3.1 DDL (Data Definition Language)

# 使用率最高的DDL语句
CREATE DATABASE db_name; #建库
USE db_name; #选择库
DROP DATABASE db_name; #删库
CREATE TABLE table_name( #建表
column_name_1 column_type_1 constraints,
column_name_2 column_type_2 constraints,
......
column_name_n column_type_n constraints
);
DROP TABLE table_name; #删表
ALTER TABLE table_name ADD CONSTRAINT pk_name PRIMARY
KEY(pk_column_name); #添加主键
ALTER TABLE table_name ADD CONSTRAINT uk_name unique(uk_column_name);
#添加唯一键
ALTER TABLE table_name ADD CONSTRAINT fk_name foreign key
(fk_column_name) references ref_table_name (ref_column_name); #添加
外键
ALTER TABLE table_name ADD CONSTRAINT ck_name check(ck_expression);
#添加检查约束
#创建索引
CREATE INDEX index_name ON table_name(column_name);
#以下使用率略低一些
ALTER TABLE tabl_ename MODIFY [COLUMN] column_definition
#修改字段
ALTER TABLE table_name ADD [COLUMN] column_definition [FIRST | AFTER
col_name]; #增加字段
ALTER TABLE tablename DROP [COLUMN] column_name;
#删除字段
ALTER TABLE tablename CHANGE [COLUMN] old_col_name column_definition
[FIRST | AFTER col_name]; #字段改名

3.2 TCL (Transaction Control Language)

(1) Transaction: Database transactions are used to maintain data integrity. It guarantees the atomicity of a batch of SQL operations, either completely executed or not executed at all.

(2) The database engine in MySQL MySQL supports several database engines, and not all engines support transaction processing. MyISAM and InnoDB are the most commonly used MySQL engines. The former does not support transaction processing, but the latter supports it.

(3) Common keywords for transactions:

               transaction (transaction): refers to a set of atomic SQL statements.

               rollback (rollback): The value undoes the execution of the specified SQL statement.

               commit (commit): Write the unstored SQL statement to the database.

               savepoint: A temporary location set in a transaction that can be committed or rolled back.

(4) Example:

START TRANSACTION; #开始事务
DELETE FROM USER WHERE id=4;
DELETE FROM USER WHERE id=5;
ROLLBACK; #回滚事务
START TRANSACTION; #开始事务
DELETE FROM USER WHERE id=4;
SAVEPOINT deleteA; #创建保存点deleteA
DELETE FROM USER WHERE id=5;
ROLLBACK TO deleteA; #回滚到保存点deleteA
COMMIT;

(5) Change the default commit behavior:

           By default, MySQL automatically commits transactions. Any changes made by a MySQL statement take effect immediately. If you want MySQL not to automatically commit changes, you need to set the autocommit flag value.

SET autocommit=0;

3.3 DML (Data Manipulation Language)

3.3.1 Addition, modification and deletion

INSERT INTO table_name(column1,column2...columnN)
VALUES(value1,value2,...valueN); #insert
UPDATE table_name SET column1=value1,column2=value2,...columnN=valueN
[WHERE CONDITION]; #update
DELETE FROM table_name [WHERE CONDITION];
#delete

3.3.2 Query

SELECT 字段/表达式列表 FROM 表名 [LEFT/INNER JOIN 表名 ON 关联字段] WHERE
字段/表达式条件 GROUP BY 分组 ORDER BY 排序 [ASC/DESC] HAVING 聚合函数条
件;

3.4 DCL (Data Control Language)

DCL is used to define access permissions and security levels, create users, and authorize them. DCL is usually used by database administrators (DB Administrator), and programmers don't use it much.

(1) Create a user

create user 用户名@IP地址 identified by '密码';

(2) Assign permissions

grant 权限1,权限2,... on 数据库.数据库对象 to 用户名@IP地址

(3) Revoke permission

revoke 权限1,...,权限n on 数据库.* from 用户名@IP地址

Guess you like

Origin blog.csdn.net/qq_55917018/article/details/127900725