3. Basics of SQL and MySQL

Better reading experience\huge{\color{red}{better reading experience}}better reading experience

3.0 References



3.1 Introduction to SQL


3.1.1 SQL concepts and features


Basic concept :

  • SQL( Structured Query Language: Structured Query Language ) is used to manage relational database management systems ( RDBMS).
  • SQLThe scope includes data insertion, query, update, and deletion, database schema creation and modification, and data access control.
  • Such databases include: MySQL, SQL Server, Access, Oracle, Sybase, DB2etc.
  • SQL1986It became ANSIan (American National Standards Institute) Standard in 2000 1987and an International Organization for Standardization (ISO) standard in 2010.

Features :

  • Comprehensive and unified: integrates the functions of data definition language, data manipulation language, and data control language into one, and the language style is unified;
  • Highly non-procedural: no knowledge of access paths is required. The selection of access path and the operation process of SQL are automatically completed by the system;
  • Set-oriented operation mode: using the set operation mode, the object of the addition, deletion, modification and query operation can be a set of tuples;
  • Provide multiple usage methods with the same grammatical structure: SQL is both an independent language and an embedded language;
  • The language is concise, easy to learn and use: easy.

3.1.2 Types of SQL language


  • Data Query Language (DQL, Data Query Language): The basic structure is a query block composed of SELECT clause, FROM clause, and WHERE clause.
  • Data Manipulation Language (DML, Data Manipulation Language): In the SQL language, it is an instruction set responsible for performing data access work on database objects, with INSERT, UPDATE, and DELETE as the core, representing insert, update, and delete respectively. Instructions that data-centric applications must use.
  • Database Definition Language (DDL, Data Definition Language): A language used to describe real-world entities to be stored in a database.
  • Database Control Language (DCL, Data Control Language): Statements used to set or change database user or role permissions, including (grant, deny, revoke, etc.) statements.

What we usually call CRUD is actually CRUD (Create/Retrieve/Update/Delete)


3.1.3 SQL Basic Conventions


SQL is case insensitive :

  • SQLInsensitive to case: so SELECTand SELECTare the same, but it is still recommended to SQLwrite the command statement in pure uppercase letters, which has the following advantages:
    • Improve readability: SQLUsing pure uppercase in command statements can make keywords, functions, table names and other parts more eye-catching and easy to read and understand.
    • Unified standardization: The use of pure uppercase can unify SQLthe writing standard of command statements, which is convenient for code maintenance and modification.
    • Avoid ambiguity: SQLUse pure uppercase in command statements to avoid grammatical errors and ambiguities caused by mixed case.
  • Although SQLis not case sensitive, SQLit is still good habit and best practice to use plain uppercase in command statements.

Semicolons and commas for SQL statements :

  • Some database systems require SQLa semicolon at the end of each statement.
  • A semicolon is a standard way of separating each statement in a database system so that more than one statement SQLcan be executed in the same request to the server .SQL
  • Commas are often used to separate column names or elements such as expressions, values, or subqueries.
  • As for some long statements using commas, there are different separation rules in different database systems.

SQL support comments :

  • By using --or #to write the comment content, you can also use /* 注释内容 */to make multi-line comments.

3.1.4 Introduction to MySQL


  • MySQLRelational Database Management System
  • MySQLSupport for large databases. Can handle large databases with tens of millions of records.
  • MySQLUse standard SQLdata language forms.
  • MySQLIt can run on multiple systems and supports multiple languages.

3.2 Basic Grammar


This section explains SQLthe basic syntax, and the specific syntax examples use MySQLDemo.


3.2.1 Database Definition Language (DDL)


database operation


CREATE DATABASECreate a database with :

CREATE DATABASE 数据库名

In order to support Chinese, we can set the encoding format when creating:

CREATE DATABASE 数据库名 DEFAULT CHARSET utf8 COLLATE utf8_general_ci

Use DROP DATABASEto drop a database:

DROP DATABASE 数据库名

For example MySQLto create the database Stu_Course in:

CREATE DATABASE Stu_Course;

MySQLTo switch and use the specified database in :

USE Stu_Course;

Set the character set (if the default character set is not set during creation, switch to the database that needs to be modified):

SET NAMES utf8mb4;

Check MySQLthe current character set:

SHOW VARIABLES LIKE 'character_set%';

SQL data type


The following data types are used for string storage:

  • CHAR(n): Any character string can be stored, but it has a fixed length of n. If the inserted length is less than the defined length, it will be filled with spaces.
  • VARCHAR(n): Any number of strings can also be stored, the length is not fixed, but cannot exceed n, and will not be filled with spaces.

The following data types are used to store numbers:

  • SMALLINT: Used to store small integers, the range is (-32768, 32767);
  • INT: Used to store general integers, the range is (-2147483648, 2147483647);
  • BIGINT: Used to store large integers, the range is (-9,223,372,036,854,775,808, 9,223,372,036,854,775,807);
  • FLOAT: Used to store single-precision decimals;
  • DOUBLE: Decimals used to store double precision;

The following data types are used to store time:

  • DATE: storage date;
  • TIME: storage time;
  • YEAR: storage year;
  • DATETIME: used for mixed storage date + time;

create table


After the database is created, we generally use CREATE TALBEthe statement to create a table:

CREATE TABLE 表名(
    列名 数据类型[列级约束条件],
    列名 数据类型[列级约束条件],
             ...
    [,表级约束条件]
)

create index


When the amount of data becomes very large, by creating an index, the query efficiency can be greatly improved:

# 创建索引
CREATE INDEX 索引名称 ON 表名 (列名)

# 查看表中的索引
SHOW INDEX FROM 表名

Delete the index:

DROP INDEX 索引名称 ON 表名

For example :

In MySQL, create an ordinary index for the "Grade" field of the SC table, named sc_idx.

CREATE INDEX sc_idx ON sc (Grade);

Note :

  • Although adding an index will make the query more efficient, we cannot overuse the index;
  • While indexing brings us high-speed query efficiency, it will also generate additional indexing overhead when data is updated, and it will also occupy disk resources.
  • In addition, MySQLthe indexing mechanism of will be introduced in detail in subsequent chapters.

column-level constraints


There are six types of column-level constraints:

  • Primary key: PRIMARY KEY;
  • foreign key: FOREIGN KEY;
  • unique: UNIQUE;
  • Check: CHECK (not supported by MySQL);
  • Default: DEFAULT;
  • NOT NULL/NULL: NOT NULL/NULL.

table-level constraints


There are four types of table-level constraints: primary key, foreign key, unique, check

For example :

MySQLCreate the following table in :

column name type of data width allow null values default value primary key foreign key illustrate
Cno CHAR 4 no yes course number
Cname CHAR 40 yes course name
Cpno CHAR 4 yes yes Preliminary class
He believes SMALLINT yes credit
CREATE TABLE Course (
	Cno CHAR(4) NOT NULL COMMENT '课程号',  # NOT NULL 非空约束;COMMENT '描述说明'
	Cname CHAR(40) NULL COMMENT '课程名',
	Cpno CHAR(4) NULL COMMENT '先行课',
	Ccredit SMALLINT NULL COMMENT '学分',
	PRIMARY KEY (Cno),  # 设置主键
	FOREIGN KEY (Cpno) REFERENCES Course(Cno)  # 设置外键关联
)ENGINE=INNODB DEFAULT CHARSET=utf8;  # ENGINE 设置存储引擎,CHARSET 设置字符集

modify table


If we want to modify the table structure, we can ALTER TABLEmodify it through:

ALTER TABLE 表名 
	[ADD 新列名 数据类型[列级约束条件]]
	[DROP COLUMN 列名[RESTRICT|CASCADE]]
	[ALTER COLUMN 列名 新数据类型]
  • ADD: add a new column
  • DROP: delete a column, support can add RESTRICTor CASCADE:
    • The default is RESTRICT, which means that if this column is referenced to this column as a constraint or view of other tables, it cannot be deleted;
    • Instead, CASCADEit will force the constraints and views that refer to this column to be deleted together.
  • ALTE: to modify the properties of this column.

For example :

Add a column MySQLto the table in , the field name is (course type), the type is , the length is 10, and null values ​​are allowed:CourseCtypeCHAR

ALTER TABLE Course 
ADD Ctype CHAR(10) NULL COMMENT '课程类型';

Remove the Ctype field:

ALTER TABLE Course 
DROP Ctype;

delete table


We can drop tabledelete a table by:

DROP TABLE 表名[RESTRICT|CASCADE]

Among them, RESTRICT and CASCADE have the same effect.

For example :

MySQLDrop tables in Course:

DROP TABLE Course;

3.2.2 Database Manipulation Language (DML)


insert data


Use INSERT INTOthe statement to insert a piece of data (a record) into the database:

INSERT INTO 表名 VALUES(1,2,3)

If the inserted data corresponds to the column one by one, then the column name can be omitted, but if you want to insert data to the specified column, you need to give the column name:

INSERT INTO 表名(列名1, 列名2) VALUES(1,2)

We can also insert multiple pieces of data into the database at one time:

INSERT INTO 表名(列名1, 列名2) VALUES(1,2), (1,2), (1,2)

For example :

In MySQLa table in SC:

Sno Cno Grade
200215121 1 92

Insert a piece of data{200215122, 2, 90}

INSERT INTO SC(Sno, Cno, Grade) VALUES(200215122, 2, 90);

change the data


We can UPDATEupdate the data in the table through the statement:

UPDATE 表名 SET 列名=,... WHERE 条件

For example :

In MySQL, change the credits with course number "2" in the Course table to 4:

UPDATE Course SET Ccredit=4 WHERE Cno='2';

delete data


We can DELETEdelete data in a table by using:

DELETE FROM 表名

In this way, all the data in the table will be deleted, and we can also use WHEREto add conditions to delete only the specified data:

DELETE FROM 表名 WHERE 条件

For example :

In MySQL, delete Coursethe data with course number "2" in the table:

DELETE FROM Course WHERE Cno='2';

3.2.3 Database Query Language (DQL)


single table query


Single-use SELECTstatement for single-table query:

# 指定查询某一列数据
SELECT 列名[,列名] FROM 表名

# 会以别名显示此列
SELECT 列名 别名 FROM 表名

# 查询所有的列数据
SELECT * FROM 表名

# 只查询不重复的值
SELECT DISTINCT 列名 FROM 表名

Add WHEREa clause to limit the query target, and supports regular expressions:

SELECT * FROM 表名 WHERE 条件

For example :

In MySQL, SCquery all student information of students with scores greater than 90 in the table:

SELECT * FROM SC WHERE Grade > 90;

Common query conditions


  • General comparison operators, including =, >, <, >=, <=, !=etc., among which !=can also be <>represented by ;
  • Is it in the set: IN, NOT IN;
  • Character fuzzy matching: LIKE, NOT LIKE;
  • Multi-condition join query: AND, OR, NOT;

For example :

In MySQL, query the student number Sno of the student whose name's second character is "rain" or "jade" in the Student table:

SELECT Sno FROM Student WHERE Sname LIKE '_雨%' OR Sname LIKE '_玉%'; 

Sort query


ORDER BYSort the query results by :

SELECT * FROM 表名 WHERE 条件 ORDER BY 列名 ASC|DESC

Use ASCto indicate ascending order, use DESCto indicate descending order, the default is ascending order.

It is also possible to add multiple sorts at the same time:

SELECT * FROM 表名 WHERE 条件 ORDER BY 列名1 ASC|DESC, 列名2 ASC|DESC

In this way, the values ​​of column name 1 will be sorted first, and each group of data with the same column name 1 will be sorted according to the value of column name 2.

For example :

In MySQL, SCquery all the information of the students whose scores are greater than 90 in the table and sort them according to the score from large to small:

SELECT * FROM SC WHERE Grade > 90 ORDER BY Grade DESC;

aggregate function


Aggregate functions are generally used for statistics, including:

  • COUNT([DISTINCT]*)Count all rows (DISTINCT means deduplication);
  • COUNT([DISTINCT]列名)Count the sum of values ​​in a column;
  • SUM([DISTINCT]列名)Find the sum of a column (note that it must be of numeric type);
  • SUM([DISTINCT]列名)Find the average value of a column (note that it must be a numeric type);
  • MAX([DISTINCT]列名)Find the maximum value of a column;
  • MIN([DISTINCT]列名)Find the minimum value of a column;

General usage:

SELECT COUNT(DISTINCT 列名) FROM 表名 WHERE 条件 

For example :

In , calculate the average grade, highest score, and lowest score of students in course "2" MySQLthrough the table:SC

SELECT AVG(Grade) AS '平均成绩', MAX(Grade) AS '最高分', MIN(Grade) AS '最低分'
FROM SC
WHERE Cno = '2';

Grouping and paging queries


To GROUP BYgroup query results, it needs to be used in conjunction with aggregation functions:

SELECT SUM(*) FROM 表名 WHERE 条件 GROUP BY 列名

Add HAVINGto restrict the grouping criteria:

SELECT SUM(*) FROM 表名 WHERE 条件 GROUP BY 列名 HAVING 约束条件

Add LIMITto limit the number of queries, only take the first n results:

SELECT * FROM 表名 LIMIT 数量

A lot of query data can paginate the results:

SELECT * FROM 表名 LIMIT 起始位置,数量

For example :

In MySQL, summarize the student numbers and total grades of students with a total score greater than 200 points:

SELECT Sno, SUM(Grade) AS '总成绩'
FROM SC
GROUP BY Sno
HAVING SUM(Grade) > 200;

Outer join query


In SQL, the following join queries are supported:

  • INNER JOIN: returns the row if there is at least one match in the table;
  • LEFT JOIN: return all rows from the left table even if there is no match in the right table;
  • RIGHT JOIN: return all rows from the right table even if there is no match in the left table;
  • FULL JOIN: Return rows as long as there is a match in one of the tables.

In MySQL, the outer join query is used to combine multiple tables for query. There are three ways of outer join query:

  • INNER JOIN(Inner join, or equivalence join): Obtain the records of the field matching relationship in the two tables, that is, return the intersection of the two tables that meet the conditions .
  • LEFT JOIN(Left join): Get all the records in the left table. Even if the right table has no corresponding matching records, that is, return the intersection of the two tables that meet the conditions, and return all the data in the left table, while the missing data in the right table will be Use NULLinstead .
  • RIGHT JOIN(Right join): On LEFT JOINthe contrary, return the intersection of two tables that meet the conditions, and return all the data in the right table, and the missing data in the left table will be NULLreplaced .

For example :

In MySQL, query the course selection information of all students:

SELECT Student.*, SC.Cno, SC.Grade
FROM Student
LEFT JOIN SC
ON Student.Sno = SC.Sno;

self join query


In addition to the above join queries, MySQLself join queries are also supported.

Calculate the Cartesian product of the table itself and the table to get the result, but since the table names are the same, an alias must be created first:

SELECT * FROM 表名 别名1, 表名 别名2

nested query


Use the result of a query as a condition of another query, such as:

SELECT * FROM 表名 WHERE 列名 = (SELECT 列名 FROM 表名 WHERE 条件)

3.2.4 Database Control Language (DCL)


create user


CREATER USERCreate users with :

CREATE USER 用户名 IDENTIFIED BY 密码;

It is also possible without a password:

CREATE USER 用户名;

For example :

Create a user in MySQL:

CREATE USER 'LYS' IDENTIFIED BY '1145141919'; 

Use @to restrict the login IP address of the user to log in, %which means that all IP addresses are matched, and any IP address is used by default.

CREATE USER 'LYS'@'114.114.19.19' IDENTIFIED BY '514180';

login user


cmdLogin via mysql:

mysql -u 用户名 -p

After entering the password, you can log in to this user. Let's enter the following command to see if you can access all databases:

SHOW DATABASES;

Although this user can log in successfully, but cannot view the complete database list, this is because this user does not have permission yet !


user authorization


We can authorize a database user through rootuser usage :grant

GRANT ALL|权限1,权限2...(1,...) ON 数据库.TO 用户 [WITH GRANT OPTION]

Among them, all means to grant all permissions. When the database and table are *, it means to authorize all databases and tables. If it is added at the end WITH GRANT OPTION, the authorized user can continue to authorize the obtained authorization to other users.

We can use REVOKEto revoke a permission:

REVOKE ALL|权限1,权限2...(1,...) ON 数据库.FROM 用户

For example :

In MySQL:

GRANT ALL ON * TO 'LYS' WITH GRANT OPTION;  #给 LYS 用户授权所有数据库的权限且可以给其他用户授权
REVOKE ALL ON * FROM 'LYS';  # 收回 LYS 的全部权限QAQ

3.2.5 View


The nature of the view


  • The database can be regarded as a building, the rooms inside are regarded as tables, and the people in the rooms are specific data;
  • Then the view is equivalent to opening a "window" on the room to view the data according to the user's needs;
  • This "window" can be adjusted (modified), but in any case the modification cannot affect the people in the room (actual data);
  • Therefore, the essence of a view is a virtual table .

create view


Views are created by CREATE VIEW;

CREATE VIEW 视图名称(列名) AS 子查询语句 [WITH CHECK OPTION];

WITH CHECK OPTIONIt means that after creation, if the data in the view is updated, whether to satisfy the conditional expression in the subquery, if it is not satisfied, it will not be inserted. After creation, we can use the statement to directly query the data SELECTon the view. Therefore, also Based on the view, other views can be derived.

Note :

  • If the view is derived from more than two basic tables, the view does not allow updates.
  • The and operations are not allowed on a view whose fields are derived from field expressions or constants, INSERTbut the operation UPDATEis allowed DELETE.
  • A view does not allow updates if its fields come from a set function.
  • A view does not allow updates if the view definition contains GROUP BYa clause.
  • DISTINCTUpdates are not allowed for a view if the view definition contains the phrase.
  • FROMIf there is a nested query in the view definition, and the table involved in the clause of the inner query is also the basic table from which the view is exported, the view cannot be updated.
  • A view defined on a view that does not allow updates is also not allowed to be updated.

delete view


DROPTo delete a view via :

DROP VIEW 视图名称

view example


In MySQL, create a v_stu_cview called to display the student ID, name, and course ID of the course, and use the view to query the student ID number 200215122.

CREATE VIEW v_stu_c AS 
SELECT s.Sno, s.Sname, c.Cno 
FROM Student s, Course c, SC sc 
WHERE s.Sno = sc.Sno AND c.Cno = sc.Cno;

SELECT * 
FROM v_stu_c 
WHERE Sno = '200215122';

3.2.6 Database Integrity


trigger


It will be triggered automatically under certain conditions . When SELECT// , it will automatically execute our pre-set content. Triggers are usually used to check the security of content. Compared with directly adding constraints, triggers are more flexible UPDATE.DELETE

The table attached to the trigger is called the basic table. When operations such as // occur on the trigger table , SELECTtwo temporary tables ( table and table, which can only be used by the trigger) will be automatically generated.UPDATEDELETENEWOLD

For example :

  • During INSERTthe operation, new content will be inserted into NEWthe table;
  • During DELETEthe operation, the old content will be moved to OLDthe table, and we can still OLDget the deleted data in the table;
  • During UPDATEoperation, the old content will be moved OLDto the table, and the new content will appear in NEWthe table.
CREATE TRIGGER 触发器名称 [BEFORE|AFTER] [INSERT|UPDATE|DELETE] ON 表名/视图名 FOR EACH ROW DELETE FROM Student WHERE Student.sno = NEW.sno

FOR EACH ROWIndicates that it will take effect for each row, and the trigger will be executed no matter which row performs the specified operation!

Check the triggers with the following command:

SHOW TRIGGERS

Remove this trigger:

DROP TRIGGER 触发器名称

affairs


concept :

  • SQLA transaction (Transaction) is a logical unit of a group of database operations. These operations are considered as a whole and must be completed or not completed to maintain data consistency.
  • If one of the operations fails, the entire transaction will not be executed, and the operations that have already been executed will be automatically rolled back (undo) to ensure data integrity and consistency.

Transactions typically operate using the following statements:

  • BEGIN TRANSACTIONOr START TRANSACTION: start a new transaction.
  • COMMIT: Commit the transaction and permanently save all operations in it to the database.
  • ROLLBACK: Undo all operations in the transaction and roll back to the state before the transaction started.

SQLTransaction processing is an important mechanism to ensure concurrency control, which can ensure data consistency and integrity when multiple users access the database concurrently .

Note :

  • In MySQL, only Innodbthe engine supports transactions, we can check the supported engines like this:
SHOW ENGINES;

MySQLThe engine is used by default Innodb, and it can be modified to other engines.

  • Avoid using lock tables (for example, through the LOCK TABLES command) to modify data during the execution of a transaction, which will affect the performance and concurrency of the transaction.

The characteristics of the transaction :

  • Atomicity: All operations in a transaction are either completed or not completed, and will not end in a certain link in the middle. If an error occurs during the execution of the transaction, it will be rolled back (Rollback) to the state before the transaction started, as if the transaction had never been executed.
  • Consistency: The integrity of the database is not violated before the transaction begins and after the transaction ends. This means that the written data must fully comply with all preset rules, including data accuracy, seriality, and the subsequent database can spontaneously complete the scheduled work.
  • Isolation: The ability of the database to allow multiple concurrent transactions to read, write and modify its data at the same time. Isolation can prevent data inconsistency caused by cross-execution when multiple transactions are executed concurrently. Transaction isolation is divided into different levels, including read uncommitted (Read uncommitted), read committed (read committed), repeatable read (repeatable read) and serialization (Serializable).
  • Persistence: After the transaction processing ends, the modification to the data is permanent, even if the system fails, it will not be lost.

Let's explore the following transactions with the following examples:

START TRANSACTION;  # 开始事务

INSERT INTO orders (customer_id, total_price) VALUES (1, 100.0);  # 向订单表中插入一个订单记录
UPDATE customers SET balance = balance - 100.0 WHERE id = 1;  # 更新客户表中对应的用户余额

COMMIT;  # 提交事务
# 一旦提交,就无法再进行回滚了!

Guess you like

Origin blog.csdn.net/LYS00Q/article/details/130140995