mysql study notes recorder

1. Share a little trick:

When defining the data type, if it is determined to be an integer, use INT; if it is a decimal, use the fixed-point type DECIMAL; if it is a string, as long as it is not a primary key, use TEXT; if it is a date and time, use DATETIME

2. After running this statement, an empty table demo.importheadhist with the same table structure as demo.importhead is created.

CREATE TABLE demo.importheadhist
LIKE demo.importhead;

3.


CREATE TABLE
(
字段名 字段类型 PRIMARY KEY
);
CREATE TABLE
(
字段名 字段类型 NOT NULL
);
CREATE TABLE
(
字段名 字段类型 UNIQUE
);
CREATE TABLE
(
字段名 字段类型 DEFAULT 值
);
-- 这里要注意自增类型的条件,字段类型必须是整数类型。
CREATE TABLE
(
字段名 字段类型 AUTO_INCREMENT
);
-- 在一个已经存在的表基础上,创建一个新表
CREATE TABLE demo.importheadhist LIKE demo.importhead;
-- 修改表的相关语句
ALTER TABLE 表名 CHANGE 旧字段名 新字段名 数据类型;
ALTER TABLE 表名 ADD COLUMN 字段名 字段类型 FIRST|AFTER 字段名;
ALTER TABLE 表名 MODIFY 字段名 字段类型 FIRST|AFTER 字段名;

4. Specify the storage engine


ALTER TABLE 表名 ENGINE=INNODB;

5. Please write an SQL statement to change the field "salesprice" in the table demo.goodsmaster to be non-repeatable and not empty.

ALTER TABLE demo.goodsmaster 
CHANGE COLUMN salesprice salesprice DECIMAL(10,2) NOT NULL UNIQUE;

6. The syntax structure of the query statement:


SELECT *|字段列表
FROM 数据源
WHERE 条件
GROUP BY 字段
HAVING 条件
ORDER BY 字段
LIMIT 起始点,行数

7.


INSERT INTO 表名 [(字段名 [,字段名] ...)] VALUES (值的列表);
 
INSERT INTO 表名 (字段名)
SELECT 字段名或值
FROM 表名
WHERE 条件
 
DELETE FROM 表名
WHERE 条件
 
UPDATE 表名
SET 字段名=值
WHERE 条件

SELECT *|字段列表
FROM 数据源
WHERE 条件
GROUP BY 字段
HAVING 条件
ORDER BY 字段
LIMIT 起始点,行数

8. Suppose the user has 2 independent stores, each with its own system. Now it is necessary to introduce a chain operation model to manage the two stores in one system. Then the first problem encountered is the need for data integration. Let's take the product information table as an example to illustrate how to integrate the product information data of two stores by using the "ON DUPLICATE" keyword.

Assuming that the product information table of store A is "demo.goodsmaster", the code is as follows:


mysql> SELECT *
    -> FROM demo.goodsmaster;
+------------+---------+-----------+---------------+------+------------+
| itemnumber | barcode | goodsname | specification | unit | salesprice |
+------------+---------+-----------+---------------+------+------------+
|          1 | 0001    | 书        | 16开          | 本   |      89.00 |
|          2 | 0002    | 笔        | 10支装        | 包   |       5.00 |
|          3 | 0003    | 橡皮      | NULL          | 个   |       3.00 |
+------------+---------+-----------+---------------+------+------------+
3 rows in set (0.00 sec)

The product information table of store B is "demo.goodsmaster1":


mysql> SELECT *
    -> FROM demo.goodsmaster1;
+------------+---------+-----------+---------------+------+------------+
| itemnumber | barcode | goodsname | specification | unit | salesprice |
+------------+---------+-----------+---------------+------+------------+
|          1 | 0001    | 教科书    | NULL          | NULL |      89.00 |
|          4 | 0004    | 馒头      |               |      |       1.50 |
+------------+---------+-----------+---------------+------+------------+
2 rows in set (0.00 sec)

Suppose we want to insert the product data of store B into the product table of store A. If there are duplicate product numbers, replace the barcode of store A with the barcode of store B, and replace store A with the product name of store B. If there is no repeated number, directly insert the product data of store B into the product table of store A. This operation can be achieved with the following SQL statement:


INSERT INTO demo.goodsmaster 
SELECT *
FROM demo.goodsmaster1 as a
ON DUPLICATE KEY UPDATE barcode = a.barcode,goodsname=a.goodsname;
-- 运行结果如下
mysql> SELECT *
    -> FROM demo.goodsmaster;
+------------+---------+-----------+---------------+------+------------+
| itemnumber | barcode | goodsname | specification | unit | salesprice |
+------------+---------+-----------+---------------+------+------------+
|          1 | 0001    | 教科书    | 16开          | 本   |      89.00 |
|          2 | 0002    | 笔        | 10支装        | 包   |       5.00 |
|          3 | 0003    | 橡皮      | NULL          | 个   |       3.00 |
|          4 | 0004    | 馒头      |               |      |       1.50 |
+------------+---------+-----------+---------------+------+------------+
4 rows in set (0.00 sec)

9. I would like to ask you to think about a question: In the commodity table demo.goodsmaster, the field "itemnumber" is the primary key, and it satisfies the auto-increment constraint. If I delete a record and insert the data again, the field "itemnumber" will appear. value is not continuous. Please think about it, how to insert data to prevent this from happening?

Answer: When adding records in the commodity table, you can judge. If you find that the itemnumber is not continuous, you can insert the data by explicitly specifying the itemnumber value, instead of omitting the itemnumber and letting it increment automatically.

ALTER TABLE demo.goodsmaster AUTO_INCREMENT=Breakpoint value

10. If I want to change the price of all products whose unit is "package" in the sales flow meter demo.trans to 80% of the original price, how can I do it?

UPDATE demo.trans AS a, demo.goodsmaster AS b SET price = price * 0.8 WHERE a.itemnumber = b.itemnumber AND b.unit = '包'

11. Foreign key constraints and association queries


-- 定义外键约束:
CREATE TABLE 从表名
(
字段 字段类型
....
CONSTRAINT 外键约束名称
FOREIGN KEY (字段名) REFERENCES 主表名 (字段名称)
);
ALTER TABLE 从表名 ADD CONSTRAINT 约束名 FOREIGN KEY 字段名 REFERENCES 主表名 (字段名);

-- 连接查询
SELECT 字段名
FROM 表名 AS a
JOIN 表名 AS b
ON (a.字段名称=b.字段名称);
 
SELECT 字段名
FROM 表名 AS a
LEFT JOIN 表名 AS b
ON (a.字段名称=b.字段名称);
 
SELECT 字段名
FROM 表名 AS a
RIGHT JOIN 表名 AS b
ON (a.字段名称=b.字段名称);

12. If your business scenario cannot use foreign key constraints due to high concurrency and other reasons, in this case, how do you ensure data consistency at the application level?

If foreign key constraints cannot be used, you can add a functional module to the application layer to ensure data integrity. For example, when deleting a record in the main table, add a function to check whether the record is applied in the slave table. If it is applied, it is not allowed to delete .

13. Because HAVING cannot be used alone, it must be used together with GROUP BY. GROUP BY is understood as grouping data, which is convenient for us to perform statistical calculations on the data in the group.

14.The difference between having and where:

The first difference is that if you need to get the required data from the associated table through a join, WHERE is to filter first and then join, and HAVING is to connect first and then filter. This point determines that WHERE is more efficient than HAVING in relational queries. Because WHERE can be filtered first and connected with a small filtered data set and the associated table , it takes up less resources and the execution efficiency is relatively high . HAVING needs to prepare the result set first, that is, use the unfiltered data set to associate, and then filter this large data set, which takes up more resources and lowers the execution efficiency.

The second difference is that WHERE can directly use fields in the table as filter conditions, but cannot use calculation functions in grouping as filter conditions; HAVING must be used in conjunction with GROUP BY, which can use grouping calculation functions and grouping fields as filter conditions condition. When data needs to be grouped for statistics, HAVING can complete tasks that WHERE cannot.

15. There is such a saying: the condition after HAVING must be the condition that contains the calculation function in the grouping, do you think it is right? Why?

 The condition after HAVING must be the condition that contains the calculation function in the group. This statement makes sense, mainly considering the efficiency of the query. Because if it is not the condition of the calculation function in the grouping, then this condition should be able to use WHERE instead of HAVING, and the query efficiency is not high.

16. Transactions have 4 main characteristics, namely atomicity, consistency, durability and isolation.

Atomicity: It means that the operations in the transaction are either all executed or not all executed, like a whole, and cannot be interrupted from the middle.

Consistency: Indicates that the integrity of the data will not be destroyed by the execution of the transaction.

Isolation: It means that when multiple transactions are executed at the same time, they do not interfere with each other. Different isolation levels have different degrees of independence from each other.

Persistence: It means that the modification of the data by the transaction is permanent and effective, and will not fail due to system failure.

Through the use of locks, transactions can be isolated from each other. Locks are used differently and have different degrees of isolation.

17.MySQL supports 4 transaction isolation levels.

READ UNCOMMITTED: You can read the changed data that has not been committed in the transaction.

READ COMMITTED: Only the changed data that has been committed in the transaction can be read.

REPEATABLE READ: Indicates that in a transaction, the value of a data read is always the same as the value read for the first time, and is not affected by data operations in other transactions. This is also the default option for MySQL.

SERIALIZABLE: Indicates that any transaction, once any operation is performed on a certain data, MySQL will lock the data until the end of the transaction, prohibiting other transactions from performing any operations on the data. 

A transaction can ensure that a series of operations in the transaction are all executed without being interrupted; or all are not executed, waiting to be executed again. Operations in a transaction are characterized by atomicity, consistency, persistence, and isolation. But this does not mean that a series of DML data operations wrapped in transactions will all succeed or all fail. You need to judge whether the operation is successful or not, and notify MySQL to complete the transaction commit or rollback operation for different situations, so as to finally ensure that all operations in the transaction succeed or fail. MySQL supports 4 different transaction isolation levels. The higher the level, the more system resources are consumed. You need to set it according to the actual situation. In MySQL, not all operations can be rolled back. Such as creating a database, creating a data table, deleting a database, deleting a data table, etc., these operations cannot be rolled back, so you have to be very careful when operating, especially when deleting a database or data table, it is best to do it first Backup to prevent misuse.

18. A transaction is to ensure that the data operations in the transaction are either executed correctly or all fail. Do you think this sentence is correct? Why?

This statement is wrong. Transactions will ensure that all operations in transaction processing are executed or not executed. If an error is encountered during execution, whether to continue or roll back needs to be handled by the programmer.

19. A view is a virtual table. We can store a query statement as a view in the database. When needed, we can treat the view as a table and query the data in it.

20.

What should a complete database design document contain?

Author's reply: Generally speaking, it should include requirements analysis, modeling (ER), logical design (such as database building and table building), physical design (such as indexing), implementation, operation and maintenance (disaster recovery and backup), etc. According to actual needs, can be further refined

21. When we develop applications, we often encounter a need to group data horizontally and vertically according to different users. The so-called horizontal grouping refers to the range of data that the user can access, such as which tables data can be seen; the so-called vertical grouping refers to the extent to which the user can access the data, such as the ability to view and change the data. , or even delete.

22. Role is a new feature introduced in MySQL 8.0, which is equivalent to a collection of permissions

23. There are two types of MySQL data backup, one is physical backup, which achieves the purpose of backup by copying data files; the other is logical backup, which achieves backup by saving the information describing the structure and content of the database. Purpose. This method of logical backup is free and widely used.

First, let's learn the tool mysqldump for data backup. It has a total of three modes: backup tables in the database; backup the entire database; backup the entire database server.

24. Required by First Normal Form: All fields are basic data fields and cannot be further split.

The second normal form requires that on the basis of satisfying the first normal form, each data record in the data table must be uniquely identifiable. And all fields must completely depend on the primary key, not only a part of the primary key.

We split the original data table into three data tables in accordance with the requirements of the second normal form.

The third normal form requires that the data table must not contain fields that can be derived from non-primary key fields on the basis of satisfying the second normal form, or, in other words, there cannot be fields that depend on non-primary key fields.

25. So, how to distinguish between entities and attributes? I offer you a principle: we should look at it from the perspective of the system as a whole. What can exist independently is an entity, and what is inseparable is an attribute. That is, attributes do not require further description and cannot contain other attributes.

26. How to convert ER model diagram into data table? By drawing the ER model, we have clarified the business logic. Now, we are going to take a very important step: converting the drawn ER model into a specific data table. Let me introduce the principle of conversion. An entity is usually converted into a data table; a many-to-many relationship is usually converted into a data table; a 1-to-1, or 1-to-many relationship is often expressed through the foreign key of the table, rather than designing a new one. data table; attributes are converted into table fields. Well, let me explain to you how to use these conversion principles in combination with the previous table to convert the ER model into a specific data table, so as to implement the abstracted data model into the specific database design.

27. I have introduced several methods to improve query performance from a design point of view: modify data types to save storage space; add redundant fields when the advantages outweigh the disadvantages; change the fields and query frequencies that are frequently queried in large tables Split low fields into separate tables; try to use not-null constraints. All of these can help you further improve the query efficiency of the system and make the applications you develop more concise and efficient.

 

28. MySQL knows what you want to do through the analyzer and how to do it through the optimizer, so it enters the executor phase
and starts executing the statement.

Guess you like

Origin blog.csdn.net/qq_35207086/article/details/124183194