当前位置:网站首页>Mysql28 database design specification
Mysql28 database design specification
2022-07-06 10:34:00 【Protect our party a Yao】
One . Fan type
1.1. Introduction to paradigm
In a relational database , About the basic principles of data table design 、 Rules are called paradigms . It can be understood as , The design structure of a data table needs to meet some design standard Level . To design a relational database with reasonable structure , Must meet certain paradigms .
1.2. What does the paradigm include
At present, there are six common paradigms of relational database , According to the paradigm level , The difference from low to high is : First normal form (1NF)、 Second normal form (2NF)、 Third normal form (3NF)、 buss - The COD paradigm (BCNF)、 Fourth normal form (4NF) And the fifth paradigm (5NF, Also called perfect paradigm ).
2.3. The concept of keys and related attributes
give an example :
Here are two watches :
Player list (player) : Player number | full name | ID number | Age | Team number
Team table (team) : Team number | head coach | Where the team is located
- Super key : For the player table , A hyperkey is any combination of player numbers or ID numbers , such as ( Player number )( Player number , full name )( ID number , Age ) etc. .
- Candidate key : It's the smallest super bond , For the player table , The candidate key is ( Player number ) perhaps ( ID number ).
- Primary key : We choose for ourselves , That is, select one of the candidate keys , such as ( Player number ).
- Foreign keys : The team number in the player table .
- Main attribute 、 Non primary property : In the player list , The main attribute is ( Player number )( ID number ), Other properties ( full name )( Age )( Team number ) It's all non primary .
2.4. First normal form (1st NF)
give an example 1:
Suppose a company wants to store the name and contact information of employees . It creates a table like this :
This table does not conform to 1NF , Because the rules say “ Each attribute of a table must have atoms ( Single ) value ”,lisi and zhaoliu Staff emp_mobile Value violates the rule . In order to make the table conform to 1NF , We should have the following table data :
give an example 2:
user The design of the table does not conform to the first paradigm
Field name | Field type | Is it a primary key | explain |
---|---|---|---|
id | INT | yes | Primary key id |
username | VARCHAR(30) | no | user name |
password | VARCHAR(50) | no | password |
user_info | VARCHAR(255) | no | User information ( Include real name 、 Telephone 、 address ) |
among ,user_info The field is user information , It can be further split into smaller granularity fields , It does not meet the requirements of the first paradigm in database design . take user_info After splitting, it is as follows :
Field name | Field type | Is it a primary key | explain |
---|---|---|---|
id | INT | yes | Primary key id |
username | VARCHAR(30) | no | user name |
password | VARCHAR(50) | no | password |
real_name | VARCHAR(30) | no | Real name |
phone | VARCHAR(12) | no | contact number |
address | VARCHAR(100) | no | Home address |
give an example 3:
The atomicity of attributes is Subjective . for example ,Employees The employee's name should be used in the relationship 1 individual (fullname)、2 individual (firstname and lastname) still 3 individual (firstname、middlename and lastname) Attribute representation ? The answer depends on the application . If the application needs to process the employee's name part separately ( Such as : For search purposes ), It is necessary to separate them . otherwise , Unwanted .
surface 1:
full name | Age | Address |
---|---|---|
Zhang San | 20 | Sanyuanli, Guangzhou City, Guangdong Province 78 Number |
Li Si | 24 | Longhua new area, Shenzhen City, Guangdong Province |
surface 2:
full name | Age | province | City | Address |
---|---|---|---|---|
Zhang San | 20 | guangdong | Guangzhou, Guangdong | Three yuan li 78 Number |
Li Si | 24 | Guangdong province, | shenzhen | Longhua New District |
2.5. Second normal form (2nd NF)
give an example 1:
League tables ( Student number , Course no. , achievement ) In relationship ,( Student number , Course no. ) You can decide your grades , But the student number can't determine the grade , The course number cannot determine the grade , therefore “( Student number , Course no. )→ achievement ” Namely Complete dependency .
give an example 2:
The game table player_game , It contains the player number 、 full name 、 Age 、 Game number 、 Attributes such as competition time and venue , Here, both candidate keys and primary keys are ( Player number , Game number ), We can use candidate keys ( Or the primary key ) To determine the following relationship :
( Player number , Game number ) → ( full name , Age , Time of the game , The venue , score )
But this data table does not satisfy the second paradigm , Because the fields in the data table still have the following correspondence :
( Player number ) → ( full name , Age )
( Game number ) → ( Time of the game , The venue )
For non primary attributes , Not completely dependent on candidate keys . What kind of problems will this cause ?
- data redundancy : If a player can play m game , Then the player's name and age are repeated m-1 Time . A game may also have n Two players participate in , The time and place of the game are repeated n-1 Time .
- Insertion exception : If we want to add a new game , But it's not clear who the players are , Then there's no way to insert .
- Delete exception : If I want to delete a player number , If you don't save the game table separately , Will delete the game information at the same time .
- Update exception : If we adjust the time of a game , Then the time of all this competition in the data table needs to be adjusted , Otherwise, there will be a different game time .
In order to avoid the above situation , We can design the player game table as the following three tables .
Table name | attribute ( Field ) |
---|---|
players player surface | Player number 、 Attributes such as name and age |
match game surface | Game number 、 Attributes such as competition time and venue |
The relationship between players and the game player_game surface | Player number 、 Game number, score and other attributes |
In this case , Each data sheet conforms to the second paradigm , This avoids the occurrence of abnormal conditions .
1NF Tell us that field properties need to be atomic , and 2NF Tell us that a table is a separate object , A watch only
Express a meaning .
give an example 3:
Defines a name Orders The relationship between , Information representing orders and order lines :
It violates the second paradigm , Because there are non primary key attributes that only depend on candidate keys ( Or the primary key ) Part of . for example , You can just go through orderid Find the order orderdate, as well as customerid and companyname, There is no need to use productid.
modify :
Orders Table and OrderDetails The table is as follows , At this time, it conforms to the second paradigm .
2.6. Third normal form (3rd NF)
give an example 1:
Department information sheet : Each department has a department number (dept_id)、 Department name 、 Department profile and other information .
Employee information form : Each employee has an employee number 、 full name 、 Department number . After the department number is listed, the Department name can no longer be 、 Department profile and other information related to the Department will be added to the employee information form .
If there is no department information table , According to the third paradigm (3NF) It should also be built , Otherwise, there will be a lot of data redundancy .
give an example 2:
Field name | Field type | Is it a primary key | explain |
---|---|---|---|
id | INT | yes | Commodity primary key id ( Primary key ) |
category_id | INT | no | Commodity categories id |
category_name | VARCHAR(30) | no | Commodity category name |
goods_name | VARCHAR(30) | no | Name of commodity |
price | DECIMAL(10,2) | no | commodity price |
The commodity category name depends on the commodity category number , It doesn't conform to the third paradigm .
modify :
surface 1: In line with the third paradigm List of commodity categories The design of the
Field name | Field type | Is it a primary key | explain |
---|---|---|---|
id | INT | yes | Commodity primary key id ( Primary key ) |
category_name | VARCHAR(30) | no | Commodity category name |
surface 2: In line with the third paradigm Commodity list The design of the
Field name | Field type | Is it a primary key | explain |
---|---|---|---|
id | INT | yes | Commodity primary key id ( Primary key ) |
category_id | INT | no | Commodity categories id |
goods_name | VARCHAR(30) | no | Name of commodity |
price | DECIMAL(10,2) | no | commodity price |
Commodity list goods By commodity category id Field (category_id) And commodity category table goods_category Association .
accord with 3NF After the data model, generally speaking ,2NF and 3NF Usually summed up in this sentence :“ Each non key attribute depends on the key , Depend on
The whole key , And there's nothing but keys ”.
3、 ... and . Anti normalization
3.1. summary
Normalization vs performance
- To meet certain business goals , Database performance is more important than normalized database .
- While standardizing data , The performance of database should be considered comprehensively .
- By adding additional fields to a given table , To significantly reduce the time required to search for information from .
- By inserting computed columns into a given table , For the convenience of inquiry .
3.2. Application, for example,
give an example 1:
Employee information is stored in employees surface in , Department information is stored in departments surface in . adopt employees In the table department_id Fields and departments Table to establish association relationship . If you want to query the name of an employee's Department :
select employee_id,department_name
from employees e join departments d
on e.department_id = d.department_id;
If you often need to do this , Connection query will waste a lot of time . Can be in employees Add a redundant field to the table department_name, So you don't have to connect every time .
3.3. New problems of anti paradigm
- Storage The space is getting bigger .
- A field in a table has been modified , Redundant fields in another table also need to be modified synchronously , otherwise Data inconsistency .
- If you use stored procedures to support data updates 、 Delete and other extra operations , If updates are frequent , Would be very Consume system resources .
- stay Small amount of data Under the circumstances , The anti normal form does not embody the performance advantage , It may also make the design of the database more complex .
3.4. Applicable scenarios of anti paradigm
When redundant information is valuable or can Greatly improve query efficiency When , We will adopt anti paradigm optimization .
Four . BCNF( Bass paradigm )
4.1. Case study
We analyze the paradigm in the following table :
In this table , A warehouse has only one administrator , At the same time, an administrator only manages one warehouse . Let's sort out the dependencies between these attributes first .
The warehouse name determines the Administrator , The administrator also decides the warehouse name , meanwhile ( Warehouse, , Item name ) The set of attributes can determine the number of this attribute . such , We can find the candidate key of the data table .
Candidate key : yes ( Administrators , Item name ) and ( Warehouse, , Item name ), Then we choose one of the candidate keys as Primary key , such as ( Warehouse, , Item name ).
Main attribute : Attributes contained in any candidate key , That is, the warehouse name , Administrator and item name .
Non primary property : The attribute of quantity .
4.2. Whether it conforms to the three paradigms
How to judge the paradigm of a table ? We need to rank according to the paradigm , Judge from low to high .
First , Every attribute of the data table is atomic , accord with 1NF The requirements of ;
secondly , Non primary attribute in data table ” Number “ Are all dependent on candidate keys ,( Warehouse, , Item name ) Determine the quantity ,( Administrators , Item name ) Determine the quantity . therefore , The data sheet complies with 2NF The requirements of ;
Last , Non primary attributes in the data table , Not passing depends on candidate keys . Therefore, the 3NF The requirements of .
4.3. The problem is
Now that the data sheet has met 3NF The requirements of , Is there no problem ? Let's look at the following :
- Add a warehouse , But we haven't stored anything yet . According to the requirements of data sheet entity integrity , The primary key cannot have a null value , So there will be Insertion exception ;
- If the warehouse changes the Administrator , We might Modify multiple records in the data table ;
- If all the goods in the warehouse are sold out , Then the warehouse name and the corresponding administrator name will be deleted .
You can see , Even if the data sheet complies with 3NF The requirements of , It's also possible to insert , Exception of updating and deleting data .
4.4. Problem solving
First, we need to confirm the cause of the exception : For the candidate warehouse attribute name ( Administrators , Item name ) It's a partial dependency , This may lead to the above exceptions . So introduce BCNF, It's in 3NF In addition, it eliminates the partial or transitive dependency of primary attributes on candidate keys .
If you're in a relationship R in ,U Primary key ,A Attribute is an attribute of the primary key , If exist A->Y,Y Main attribute , Then the relationship does not belong to BCNF.
according to BCNF The requirements of , We need to put the warehouse management relationship warehouse_keeper The table is split into the following :
Warehouse table :( Warehouse, , Administrators )
An inventory statement :( Warehouse, , Item name , Number )
In this way, there is no partial or transitive dependency of the primary attribute on the candidate key , The design of the above data sheet is in line with BCNF.
5、 ... and . Fourth normal form
give an example 1: Employee table ( Employee number , Name of employee's child , Elective courses for employees ).
In this table , The same employee may have multiple employee child names . Again , The same employee may also have multiple employee elective courses , That is, there are multivalued facts , Not in line with the fourth paradigm .
If you want to conform to the fourth paradigm , Just divide the above table into two tables , Make them have only one multivalued fact , for example : Employee table 1 ( Employee number , Name of employee's child ), Employee table 2 ( Employee number , Elective courses for employees ), Both tables have only one multivalued fact , So it conforms to the fourth paradigm .
6、 ... and . The fifth paradigm 、 Domain key paradigm
In addition to the fourth paradigm , We also have a more advanced fifth paradigm ( Also called perfect paradigm ) And domain key paradigm (DKNF).
In meeting the fourth paradigm (4NF) On the basis of , Eliminate connection dependencies that are not implied by candidate keys . If the relationship pattern R Each connection dependency in is determined by R Implied by the candidate key of , It is said that this relationship model conforms to the fifth paradigm .
Functional dependency is a special case of multivalued dependency , Multivalued dependency is actually a special case of connection dependency . But unlike functional dependency and multivalued dependency, connection dependency can be determined by Semantic direct export , But in Relational connection operation It was only reflected when . The relational pattern with connection dependency may still encounter data redundancy and insertion 、 modify 、 Delete exceptions and other problems .
The fifth paradigm deals with Lossless connection problem , This paradigm is basically No practical significance , Because lossless connections rarely occur , And imperceptible . The domain key paradigm attempts to define a The ultimate paradigm , This paradigm considers all dependency and constraint types , But the practical value is also the smallest , Only exists in theoretical research .
7、 ... and . ER Model
ER There are three elements in the model , They are entities 、 Properties and relationships .
Entity , It can be regarded as a data object , Often corresponds to real individuals in real life . stay ER In the model , use rectangular To express . Entities fall into two categories , Namely Strong entity and Weak entity . Strong entities are entities that do not depend on other entities ; A weak entity is an entity that has a strong dependency on another entity .
attribute , It refers to the characteristics of the entity . For example, the address of the supermarket 、 contact number 、 Number of employees, etc . stay ER Use... In the model ellipse To express .
Relationship , It refers to the connection between entities . For example, supermarkets sell goods to customers , It's a connection between supermarkets and customers . stay ER Use... In the model The diamond To express .
It means : Entities and attributes are not easy to distinguish . Here is a principle : We should look at it from the perspective of the whole system , What can exist independently is the entity , What cannot be further divided is the attribute . in other words , Property cannot contain other properties .
8.1. The type of relationship
stay ER Model 3 Of the three elements , Relationships can be divided into 3 Types , Namely one-on-one 、 One to many 、 Many to many .
one-on-one : The relationship between entities is one-to-one correspondence , For example, the relationship between individual and ID card information is a one-to-one relationship . A person can only have one ID card information , An ID card information only belongs to one person .
One to many : Refers to an entity on one side through a relationship , It can correspond to multiple entities on the other side . contrary , The other side of the entity through this relationship , Then it can only correspond to the entity on the only side . for instance , Let's create a new class table , And each class has multiple students , Each student corresponds to a class , Class to students is a one to many relationship .
Many to many : It means that entities on both sides of a relationship can correspond to multiple opposite entities through the relationship . For example, in the purchase module , The relationship between suppliers and supermarkets is a many to many relationship , One supplier can supply multiple supermarkets , A supermarket can also purchase goods from multiple suppliers . Another example is a course selection table , There are many subjects , There are many students in each subject , And each student can choose multiple subjects , This is the many to many relationship .
8.2. Modeling analysis
ER The model looks troublesome , But it is very important for us to control the project as a whole . If you're just developing a small application , Maybe it's enough to simply design a few watches , Once you want to design an application with a certain scale , At the beginning of the project , Build a complete ER The model is very critical . The essence of the development and application project , In fact, that is modeling .
The case we designed is Electrical business , Because the e-commerce business is too large and complex , So we did business simplification , For example SKU(StockKeepingUnit, A unit of stock ) and SPU(Standard Product Unit, Standardized product unit ) In the meaning of , We used it directly SKU, He did not mention SPU The concept of . This e-commerce business design has a total of 8 Entity , As shown below .
Address entity
User entity
Shopping cart entity
Comment entity
Commodity entity
Commodity classification entity
Order entity
Order details entity
among , user and Classification of goods Is a strong entity , Because they don't need to rely on any other entity . Others are weak entities , Because although they can exist independently , But they all depend on the user entity , So they are all weak entities . Knowing these elements , We can create... For e-commerce business ER Model , Pictured :
In this picture , Add relationship between address and user , It's a one-to-many relationship , The commodity and commodity details are shown in a pair 1 The relationship between , Goods and orders are many to many relationships . This ER Model , It includes 8 Between entities 8 Kind of relationship .
(1) You can add multiple addresses on the e-commerce platform ;
(2) Users can only have one shopping cart ;
(3) Users can generate multiple orders ;
(4) Users can post multiple comments ;
(5) A product can have multiple comments ;
(6) Each commodity category contains a variety of commodities ;
(7) An order can contain multiple items , One item can be in multiple orders .
(8) The order contains multiple order details , Because an order may contain different kinds of goods .
8.3. ER Refinement of the model
With this ER Model , We can take the whole understand The business of e-commerce . Just now ER The model shows the framework of e-commerce business , But it only includes orders , Address , user , The shopping cart , Comment on , goods , The eight entities of commodity classification and order details , And the relationship between them , It can't correspond to a specific table yet , And the association between tables . We need to take Attribute plus , use The ellipse To express , So we get ER The model is more complete .
therefore , We need to further design this ER Parts of the model , That is to refine the specific business process of e-commerce , Then put them together , Form a complete ER Model . This can help us clarify the design idea of the database .
Next , Let's analyze the attributes of each entity , As shown below .
(1) Address entity Include the user number 、 province 、 City 、 region 、 The recipient 、 contact number 、 Whether it is the default address .
(2) User entity Include the user number 、 User name 、 nickname 、 User password 、 cell-phone number 、 mailbox 、 Head portrait 、 User level .
(3) Shopping cart entity Include cart number 、 The user id 、 Product id 、 The number 、 Picture file url.
(4) Order entity Include order number 、 Consignee 、 Recipient phone 、 Total sum 、 The user id 、 payment method 、 Delivery address 、 Place an order
Time .
(5) Order details entity Include order detail number 、 The order no. 、 Name of commodity 、 Product id 、 The number .
(6) Commodity entity Include item number 、 Price 、 Name of commodity 、 Classification number 、 Whether to sell , specifications 、 Color .
(7) Comment entity Include comments id、 Comment content 、 Comment on time 、 The user id 、 Product id
(8) Commodity classification entity Include category number 、 Category name 、 Parent category number
After this subdivision , We can redesign the e-commerce business ,ER Model diagram :
8.4. ER Convert model diagram into data table
By drawing ER Model , We have sorted out the business logic , Now? , We are going to take a very important step : Put the drawn ER Model , Convert to specific data table , The following describes the principle of down conversion :
(1) One Entity Usually converted to a Data sheet ;
(2) One many-to-many , Usually it is also converted into a Data sheet ;
(3) One 1 Yes 1 , perhaps 1 For more than The relationship between , Often through the... Of the table Foreign keys To express , Instead of designing a new data table ;
(4) attribute Converted to table Field .
Actually , Any database based application project , Through this First establish ER Model , Again Convert to data table The way , Complete the design of the database . establish ER The model is not the purpose , The purpose is to sort out the business logic , Design an excellent database . It is not recommended to model for modeling , To create ER Model process to sort out ideas , This creates ER The model makes sense .
Nine . Design principle of data sheet
Combine the above , Summarize the general principles of data table design :“ Three less and one more ”
- The fewer tables, the better .
- The fewer fields in the data table, the better .
- The fewer fields in the data table, the better .
- The more primary and foreign keys you use, the better .
Be careful : This principle is not absolute , Sometimes we need to sacrifice the redundancy of data in exchange for the efficiency of data processing .
Ten . Suggestions for writing database objects
10.1. About Ku
- 【 mandatory 】 The name of the library must be controlled in 32 Within characters , Only English letters 、 Numbers and underscores , It is suggested to use English words
Female beginning . - 【 mandatory 】 Library name in Chinese and English All in lowercase , Different words use Underline Division . You must see the name and know the meaning .
- 【 mandatory 】 The name format of the library : Business system name _ Subsystem name .
- 【 mandatory 】 The database name prohibits the use of the keyword ( Such as type,order etc. ).
- 【 mandatory 】 When creating a database, you must Specify the character set explicitly , And the character set can only be utf8 perhaps utf8mb4. Create database SQL give an example :CREATE DATABASE crm_fund DEFAULT CHARACTER SET ‘utf8’ ;
- 【 Suggest 】 For the program to connect to the database account , follow According to the principle of minimum permission, the database account can only be used in one DB Next use , Not allowed to cross the library . The account used by the program In principle, there must be no drop jurisdiction .
- 【 Suggest 】 Temporary library to tmp_ The prefix , And suffixed with date ; Backup library to bak_ The prefix , And suffixed with date .
10.2. About the watch 、 Column
- 【 mandatory 】 The names of tables and columns must be controlled within 32 Within characters , The table name can only use English letters 、 Numbers and underscores , It is suggested that The beginning of an English letter .
- 【 mandatory 】 Table name 、 All column names are lowercase , Different words are divided by underline . You must see the name and know the meaning .
- 【 mandatory 】 The table name shall be strongly related to the module name , Use the first mock exam of the same module as much as possible. Uniform prefix . such as :crm_fund_item
- 【 mandatory 】 When creating a table, you must Specify the character set explicitly by utf8 or utf8mb4.
- 【 mandatory 】 Table name 、 The keyword... Is prohibited for column names ( Such as type,order etc. ).
- 【 mandatory 】 When creating a table, you must Explicitly specify the table storage engine type . If there is no special need , All are InnoDB.
- 【 mandatory 】 A watch must have comment.
- 【 mandatory 】 Use English words to express the actual meaning of the field as much as possible abbreviation . Such as : company ID, Do not use corporation_id, While using corp_id that will do .
- 【 mandatory 】 Boolean fields are named is_ describe . Such as member The table indicates whether it is enabled The member's field is named is_enabled.
- 【 mandatory 】 It is forbidden to store images in the database 、 Binary data such as files are usually very large , The amount of data increases rapidly in a short time , Database for database reads , There's usually a lot of randomization going on IO operation , When the file is large ,IO Operation time . Usually stored on a file server , The database stores only the file address information .
- 【 Suggest 】 About the primary key when building a table : The table must have a primary key (1) The primary key is required to be id, The type is int or bigint, And for auto_increment It is recommended to use unsigned No sign . (2) The fields that identify the main body of each row in the table should not be set as the primary key , It is recommended to set other fields such as user_id,order_id etc. , And establish unique key Indexes . Because if it is set as the primary key and the primary key value is random
Insert , Will lead to innodb Internal page splitting and a large number of random I/O, Performance degradation . - 【 Suggest 】 Core table ( Such as user table ) There must be a row of data Create time field (create_time) and Last update time field (update_time), Easy to find out .
- 【 Suggest 】 All fields in the table should be NOT NULL attribute , Business can be defined as needed DEFAULT value . Because use NULL Values will exist, and each row will take up extra storage space 、 Data migration is error prone 、 Problems such as deviation of calculation result of aggregate function .
- 【 Suggest 】 All that store the same data Column name and column type must be consistent ( It is generally used as an associated column , Implicit conversion of data types is automatically performed if the associated column types are inconsistent during the query , Causes the index on the column to fail , The query efficiency is reduced ).
- 【 Suggest 】 In the middle of table ( Or temporary tables ) Used to preserve the intermediate result set , Names to tmp_ start . The backup table is used to back up or grab a snapshot of the source table , Names to bak_ start . Intermediate tables and backup tables are cleaned regularly .
- 【 demonstration 】 A more standard table building statement :
CREATE TABLE user_info (
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT ' Since the primary key ',
`user_id` bigint(11) NOT NULL COMMENT ' user id',
`username` varchar(45) NOT NULL COMMENT ' Real name ',
`email` varchar(30) NOT NULL COMMENT ' User mailbox ',
`nickname` varchar(45) NOT NULL COMMENT ' nickname ',
`birthday` date NOT NULL COMMENT ' Birthday ',
`sex` tinyint(4) DEFAULT '0' COMMENT ' Gender ',
`short_introduce` varchar(150) DEFAULT NULL COMMENT ' Introduce yourself in a word , most 50 The Chinese characters ',
`user_resume` varchar(300) NOT NULL COMMENT ' User submitted resume storage address ',
`user_register_ip` int NOT NULL COMMENT ' Source of user registration ip',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ' Creation time ',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP COMMENT ' Modification time ',
`user_review_status` tinyint NOT NULL COMMENT ' User data review status ,1 For adoption ,2 It is under review ,3 For failing to pass ,4 For not yet submitted for review ',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_user_id` (`user_id`),
KEY `idx_username`(`username`),
KEY `idx_create_time_status`(`create_time`,`user_review_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=' Basic information of website users
- 【 Suggest 】 Create table time , You can use visualization tools . This ensures that the table 、 Field related conventions can be set . actually , We seldom write by ourselves DDL sentence , You can use some visual tools to create and manipulate databases and data tables . Visualization tools in addition to convenience , It can also directly help us transform the structure definition of the database into SQL Language , Facilitate the export and import of database and data table structure .
10.3. About index
- 【 mandatory 】InnoDB The primary key of the table must be id int/bigint auto_increment, And the primary key value Prohibited from being updated .
- 【 mandatory 】InnoDB and MyISAM Storage engine table , Index type must be BTREE .
- 【 Suggest 】 The name of the primary key is pk_ start , The only key is uni_ or uk_ start , The general index is idx_ start , All in lowercase , Use the name or abbreviation of the field as the suffix .
- 【 Suggest 】 Multi word columnname, Take the initials of the first few words , The last word forms column_name. Such as :sample surface member_id Index on :idx_sample_mid.
- 【 Suggest 】 Number of indexes on a single table No more than 6 individual .
- 【 Suggest 】 When building an index , Think more about establishing Joint index , And put the field with the highest differentiation at the front .
- 【 Suggest 】 In many tables JOIN Of SQL in , Ensure that the join column of the driven table has an index , such JOIN The highest efficiency of execution .
- 【 Suggest 】 When building tables or adding indexes , Make sure there's no one inside or outside Redundant index . such as : If there is already key(a,b), be key(a) For redundant index , You need to remove .
10.4. SQL To write
- 【 mandatory 】 Program side SELECT Statement must specify a specific field name , No writing *.
- 【 Suggest 】 Program side insert Statement specifies the specific field name , Don't write as INSERT INTO t1 VALUES(…).
- 【 Suggest 】 Except static table or small table (100 Within the line ),DML The statement must have WHERE Conditions , And use the index to find .
- 【 Suggest 】INSERT INTO…VALUES(XX),(XX),(XX)… here XX Do not exceed 5000 individual . Too much value, although it goes online quickly , But it will cause master-slave synchronization delay .
- 【 Suggest 】SELECT Do not use UNION, Recommended UNION ALL, also UNION The number of clauses is limited to 5 In a
Inside . - 【 Suggest 】 The online environment , Multiple tables JOIN Not more than 5 Tables .
- 【 Suggest 】 Reduce use ORDER BY, Communication with business can not be sorted , Or put the sorting on the program side .ORDERBY、GROUP BY、DISTINCT These statements are more expensive CPU, Database CPU Resources are extremely valuable .
- 【 Suggest 】 Contains ORDER BY、GROUP BY、DISTINCT Statements for these queries ,WHERE Please keep the result set filtered by the condition in 1000 Within the line , otherwise SQL It's going to be slow .
- 【 Suggest 】 Multiple for a single table alter Operations must be combined once for more than 100W The big table of rows goes on alter table, Must go through DBA to examine , And in the low peak period of business , Multiple alter Need to be integrated . because alter table Will produce Table locks , Block all writes to the table during , It could have a huge impact on the business .
- 【 Suggest 】 When operating data in batches , You need to control the transaction interval , Do what is necessary sleep.
- 【 Suggest 】 The business includes SQL No more than 5 individual . Because too long transactions will result in long lock data ,MySQL Internal Cache 、 Too much connection consumption and so on .
- 【 Suggest 】 Update statements in transactions should be based on primary key or UNIQUE KEY, Such as UPDATE… WHERE id=XX; Otherwise, there will be a gap lock , Internal expansion locking range , Results in system performance degradation , Generate deadlock .
11、 ... and . PowerDesigner Use
PowerDesigner Is a common database modeling tool for developers , Users can easily make Data flow chart 、 Conceptual data model 、 Physical data model , It almost includes the whole process of database model design , yes Sybase The company provides a complete set of integrated enterprise level modeling solutions for enterprise modeling and design .
11.1. Download and install
Download address : link :https://pan.baidu.com/s/1w81uemxnREbWYSFOESjuoA
Extraction code :jk7e
Please refer to :https://www.fujieace.com/software/powerdesigner.html
11.2. Start interface
Currently in use PowerDesigner The version is 16.5 Of . Open the software is this page , Can choose Create Model, You can also choose Do Not Show page Again, You can create it by yourself after opening the software ! It all depends on personal preference , Here I will not show this page in the later study .
“Create Model” The function of is similar to an ordinary file , The document can be stored separately or classified .
“Create Project” Is similar to a folder , Be responsible for the centralized classification and storage of related documents .
11.3. Conceptual data model
Common models are 4 Kind of , Namely conceptual model (CDM Conceptual Data Model) , The physical model (PDM,Physical Data Model) , An object-oriented model (OOM Objcet Oriented Model) and business model (BPM Business Process Model) , Let's first create a conceptual data model .
Conceptual Data Model: Conceptual data model , It takes substance - contact (Entity-RelationShip, E-R) Theory based , And the theory is extended . It models information from the user's point of view , It is mainly used for conceptual level design of database .
Usually people first abstract the real world into the conceptual world , Then turn the conceptual world into the machine world . let me put it another way , Is to abstract the objective objects in the real world into entities (Entity) And contact (Relationship), It doesn't depend on a specific computer system or some DBMS System , This model is what we call CDM; And then CDM Convert to a... On the computer DBMS Supported data models , Such a model is the physical data model , namely PDM.
CDM Is a collection of strictly defined model elements , These model elements accurately describe the static characteristics of the system 、 Dynamic characteristics and integrity constraints , It includes data structure 、 Data operation and integrity constraints .
- Data structures are expressed as entities and attributes ;
- The data operation is expressed as the insertion of records in the entity 、 Delete 、 modify 、 Query and so on ;
- Integrity constraints are expressed as data's own integrity constraints ( Such as data type 、 Check 、 Rules etc. ) Referential integrity constraints between and data ( If contact 、 Inheritance, connection, etc )
11.3.1. Entity 、 Definition of attributes and identifiers
Entity (Entity):
Also known as instance , Corresponding to... That can be distinguished from other objects in the real world “ event ” or “ thing ”. for example , Every student in the school , Every operation in the hospital . Each entity has a set of properties that describe the characteristics of the entity , It's called attribute , An entity is described by several attributes . For example, the student entity can be determined by the student number 、 full name 、 Gender 、 date of birth 、 Department 、 Year of enrollment and other attributes .
Entity set (EntitySet):
Is a collection of entities of the same type and nature . For example, the set of all students in the school can be defined as “ Student ” Entity set ,“ Student ” Each entity in the entity set has a student number 、 full name 、 Gender 、 date of birth 、 Department 、 Year of enrollment, etc .
Entity type (EntityType):
It is a set of common properties of each entity in the entity set , for example “ In patients with ” The entity type is : In patients with { Outpatient No , full name , Gender , Age , ID number …}. An entity is an instance of an entity type , Where the meaning is clear , Entity 、 Entity types are often used interchangeably . Each entity in an entity type contains one or a set of attributes that uniquely identify it , These attributes are called identifiers of entity types (Identifier), Such as “ Student number ” Is the identifier of the student entity type ,“ full name ”、“ Date of birth ”、“ Letter address ” Together, “ citizens ” Identifier of the entity type . Some entity types can have several sets of attributes as identifiers , Select one of the attributes as the primary identifier of the entity type , Others are used as secondary identifiers .
11.3.2. Entity 、 Expression of attributes and identifiers
11.3.3. Create a new conceptual data model
- choice File–>New, The dialog box as shown in the figure pops up , choice CDM Model ( Conceptual data model ) Build a model .
Click on the top ok, You can see the conceptual model on the left in the figure below 1, You can customize the name of the conceptual model , The most used in the conceptual model is as shown in the figure Entity( Entity ),Relationship( Relationship
Entity Entity
Check in the right border Entity This function , The following box appears , What needs attention is writing name When ,code Complete by yourself ,name It can be English or Chinese , however code It has to be in English .
Fill in entity fields
General Medium name and code After filling , I can click Attributes( attribute ) To set up name( name ),code( Field names in the database ),Data Type( data type ) ,length( Length of data type ). - Name: The entity name is generally Chinese , Such as forum users
- Code: Entity code , Usually in English , Such as XXXUser
- Comment: notes , A detailed description of this entity
- Code attribute : Code name , Usually in English UID DataType
- Domain Domain , Indicates the value range of the attribute. For example, you can create 10 The address field of characters
- M:Mandatory Mandatory properties , Indicates that the attribute is required . Can't be empty
- P:Primary Identifer Is the primary identifier , Represents the unique identifier of the entity
- D:Displayed Show it , Check all by default
Here is an illustration of name and code The way to name
Set primary identifier
If you don't want the system to generate identifiers automatically but set them manually , So switch to Identifiers tab , Add a row Identifier, Then click... In the upper left corner “ attribute ” Button , Then click... In the pop-up ID attribute setting dialog box “ add rows ” Button , Select the attribute used in this identification . For example, set the student number as the identification of the student entity .
Entity relations
Similarly, create a class entity ( Here's the thing to watch out for , After clicking the right function button, you need to click the mouse pointer button or right-click the mouse , Otherwise, it's easy to operate disorderly , Just pay attention to this ), And then use Relationship( Relationship ) This button can connect the relationship between the students and the class , One to many ( Class to student ) Or many to one ( The students are interested in the class ) The relationship between . As shown in the figure
It's important to note that clicking Relationship This button , It connects the class with the students , It's just a line , Then double click the line to edit it , stay General Start this name and code
above name and code After you get up, you can go to Cardinalities Check out the relationship between class and students , You can see at one end of the class is a line , At one end of the student are three , It represents the one to many relationship between class and students, that is one Yes many The relationship between , Click application , Then make sure that
11.4. Physical data model
Let's talk about the physical data model , in the future Regular use The physical model is the data . open
PowerDesigner, And then click File–>New Model Then select the physical data model as shown in the figure below , The name of the physical data model comes from itself , Then select the database you use .
Create the main page as shown in the figure , But the button on the right is slightly different from the conceptual model , The three most commonly used physical models are table( surface ) , view( View ) , reference( Relationship ) ;
Click on the right side first table This button and then click on the new physical model , You can create a new table , Then double click new as shown in the figure below , stay General Of name and code Fill in what you need , Click on the app ), Here's the picture :
And then click Columns, As shown in the following figure , It's simple , It's important to note that P(primary Primary key ) , F (foreign key Foreign keys ) ,M(mandatory Compulsory , Representative cannot be empty ) These three .
Set up the self increment of student number here (MYSQL The self increasing inside is this AUTO_INCREMENT), The class number is the same , Don't go into details !
Just check the sign at the following point , It's set up to be self increasing
When it's all finished, it's as shown in the figure below .
The physical model of the class can be created as shown in the figure below
After completion, as shown in the figure below
The settings above are as shown in the figure above , And then here's the key , Click the right button Reference This button , Because the class is one to many to the students , So pull the mouse from the student to the class, as shown in the figure below , The student table will change , A line has been added to the student list , This row is the primary key of the class table as the foreign key of the student table , Connect the class table with the student table .( If you look closely, you can see the difference .)
Do the above , You can double-click a line in the middle , As shown in the figure below , modify name and code that will do
But here's the thing , After modification, the result is as shown in the figure below , There's no way to go directly like the conceptual model , After modification, it will be displayed on the middle line , Just understand yourself .
Learning many to one or one to many relationships , Next, learn the relationship between many pairs , In the same way, I set up my teacher table , There is no narration here , Remember that the number of teachers increases by themselves , As shown in the figure below
Here's the key to many relationships , Because the many to many relationship of physical model needs an intermediate table to connect , Here's the picture , Set only one field , Primary key , Self increasing
Click application , Then set the Columns, Just add one field
This is set field increment , It has been described several times before
After setting, as shown in the figure below , Note that the side with the arrow is a , The side without arrow is more , That is, the one to many, many to one relationship needs to be clarified , Students can also have many teachers , Teachers can also have a lot of students , So students and teachers can be the main body ;
You can see the changes in the relationship table between students and teachers after adding the relationship
11.5. Conceptual model to physical model
11.5.1. As shown in the figure below, first open the conceptual model diagram , And then click Tool, As shown in the figure below
After completion, as shown in the figure below , The modified physical model will open itself , It should be noted that the data types of these tables have changed by themselves , And there are two primary keys in the middle table , Double primary keys ,
11.6. Physical model to conceptual model
Then the interface as shown in the figure below appears , Then change physics to concept , Click apply to confirm
Click OK to open the page as shown in the figure below , See for yourself what's going on , If it is converted to oracle Of , Data types change , such as Varchar2 wait );
边栏推荐
- 15 医疗挂号系统_【预约挂号】
- ByteTrack: Multi-Object Tracking by Associating Every Detection Box 论文阅读笔记()
- 使用OVF Tool工具从Esxi 6.7中导出虚拟机
- MySQL storage engine
- Not registered via @enableconfigurationproperties, marked (@configurationproperties use)
- Jar runs with error no main manifest attribute
- Super detailed steps to implement Wechat public number H5 Message push
- A necessary soft skill for Software Test Engineers: structured thinking
- Vscode common instructions
- MySQL实战优化高手11 从数据的增删改开始讲起,回顾一下Buffer Pool在数据库里的地位
猜你喜欢
MySQL34-其他数据库日志
MySQL combat optimization expert 04 uses the execution process of update statements in the InnoDB storage engine to talk about what binlog is?
Mysql27 index optimization and query optimization
How to make shell script executable
MySQL30-事务基础知识
A necessary soft skill for Software Test Engineers: structured thinking
PyTorch RNN 实战案例_MNIST手写字体识别
Pytorch RNN actual combat case_ MNIST handwriting font recognition
If someone asks you about the consistency of database cache, send this article directly to him
In fact, the implementation of current limiting is not complicated
随机推荐
Google login prompt error code 12501
第一篇博客
Not registered via @enableconfigurationproperties, marked (@configurationproperties use)
Case identification based on pytoch pulmonary infection (using RESNET network structure)
Notes of Dr. Carolyn ROS é's social networking speech
软件测试工程师发展规划路线
Database middleware_ MYCAT summary
Time complexity (see which sentence is executed the most times)
Cmooc Internet + education
MySQL storage engine
[programmers' English growth path] English learning serial one (verb general tense)
Mysql35 master slave replication
颜值爆表,推荐两款JSON可视化工具,配合Swagger使用真香
Sed text processing
Solution to the problem of cross domain inaccessibility of Chrome browser
MySQL Real Time Optimization Master 04 discute de ce qu'est binlog en mettant à jour le processus d'exécution des déclarations dans le moteur de stockage InnoDB.
MySQL36-数据库备份与恢复
MySQL实战优化高手07 生产经验:如何对生产环境中的数据库进行360度无死角压测?
What should the redis cluster solution do? What are the plans?
Transactions have four characteristics?