当前位置:网站首页>Some experience in database table structure design
Some experience in database table structure design
2022-06-13 10:35:00 【Ant richlab front end team】
A good table structure design can reduce the amount of development , It can also improve some scalability , Just sort out a little bit of experience from my daily design table structure , Experience
1.0 The basic requirements
- Naming specification , Naming readable , The same business module uses the same prefix
- Do logical deletion , No physical deletion
- Do not associate primary and foreign keys , Maintain... In the business logic of the program
2.0 It doesn't need to be strictly observed 3NF, Reduce table association through business field redundancy
To understand the three paradigms in a popular way , Great for database design . In database design , In order to better apply the three paradigms , We must understand the three paradigms in a popular way ( Popular understanding is sufficient understanding , It's not the most scientific and accurate understanding ):
- First normal form :1NF It's an atomic constraint on properties , Properties are required to be atomic , It can't be broken down
- Second normal form :2NF It's a constraint on the uniqueness of records , The record is required to have a unique identification , That is, the uniqueness of the entity
- Third normal form :3NF It's a constraint on field redundancy , That is, any field cannot be derived from other fields , It requires that the fields are not redundant
No redundant database design can be done . however , A design without redundancy is not necessarily the best design
The relationship between the underlying table and its fields , Try to satisfy the third paradigm . however , Database design to meet the third paradigm , It's often not the best design . In order to improve the efficiency of the database , It's often necessary to lower the paradigm standards : Add redundancy appropriately , To achieve the purpose of exchanging space for time
For example, the above basic table for storing goods .“ amount of money ” The existence of this field , Indicates that the design of the table does not satisfy the third normal form , because “ amount of money ” Can be “ The unit price ” multiply “ Number ” obtain , explain “ amount of money ” It's a redundant field . however , increase “ amount of money ” This redundant field , It can improve the speed of query statistics , This is how space is exchanged for time
3.0 Common common fields
- deleted_at The default is null( Most of the orm Default query null)
- sort Non essential Default yes 1, Page presentation often uses
- version Non essential , The default is 1, Optimistic lock needs
- created_at Creation time
- updated_at Update time
- created_by founder
- updated_by Updated by
- remark Non essential remarks
4.0 A table represents multi-dimensional basic information
Take the cascading information of the tree structure of province and city as an example , We can design 3 A watch , And then associate them separately , But we can also design a table , It will be more concise ,3 A watch , The design is as follows :
// Provincial table
CREATE TABLE `province` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(6) NOT NULL,
`name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=35 DEFAULT CHARSET=utf8;
// City table
CREATE TABLE `city` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(6) NOT NULL,
`name` varchar(20) NOT NULL,
`provincecode` varchar(6) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=343 DEFAULT CHARSET=utf8;
// county , District Table
CREATE TABLE `area` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(6) NOT NULL,
`name` varchar(20) NOT NULL,
`citycode` varchar(6) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3145 DEFAULT CHARSET=utf8;
Copy code This is no problem , Change to a table design , as follows :
CREATE TABLE `region` (
`region_id` varchar(10) NOT NULL COMMENT ' Region key number ',
`region_name` varchar(50) NOT NULL COMMENT ' Area name ',
`region_short_name` varchar(10) DEFAULT NULL COMMENT ' Regional abbreviation ',
`region_code` varchar(20) DEFAULT NULL COMMENT ' Administrative region number ',
`region_parent_id` varchar(10) DEFAULT NULL COMMENT ' Region parent id',
`region_level` int(2) DEFAULT NULL COMMENT ' Regional level 1- province 、 Autonomous region 、 Municipalities directly under the central government 2- Prefecture level cities 、 region 、 autonomous prefecture 、 League 3- Municipal district 、 county-level city 、 county ',
PRIMARY KEY (`region_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=' District Table ';
Copy code adopt region_level This field adds a dimension information to the data , Just express the information of a piece of data , And then through region_parent_id To express the relationship , Such a table can express , When doing a query like this , All the information can be found in one table , It's convenient
This design is used in Basic data design It is very convenient , This kind of table structure changes less , newly added , Change the table structure infrequently , such as , Categorization information , Department information
Can't abuse , For example, students , class , It's not suitable , For example, the Rocco scene , floor , Booth , Frequent operation , And it does not conform to the three paradigms
5.0 1:n Design flexibility
1 To many , They are also used frequently , for example : Class and students , Departments and employees , Customers and orders , Categories and Commodities , General table building principles : From table ( In many ways ) Create a field , The field points to the main table as a foreign key ( a party ) Primary key of
Looking for pictures on the Internet
however , Sometimes we encounter a more complicated one to many relationship , We have taken the commonly used experiments in the field of marketing as an example , Suppose we need to edit the page , Different versions of components , Experimentalize , According to the design above , The table structure is designed as follows :
The table structure is designed as follows :
So we need to be in the page table , Add component table experiment id Field , And then in correspondence with pageService,componentService Add corresponding configuration method , as time goes on , We found it very good to do experiments , Do an experiment for everything , Like content , Launch plan , According to the above design , We need to be in the content table , Add... To the launch schedule experiment id Field , Write the corresponding configuration method , Very cumbersome change , It's not flexible
If we add an experiment configuration table , hold 1:n Transform into 1: 1, Change to the following :
Here we add an experiment configuration table , adopt targer_id,target_type, The experimental configuration information is independent , Do not change the original page table and component table , At the same time, in terms of domain design , We separate the experimental configuration information in our own field , So at the code level , It is also worth paying attention to the relevant experiments service, The interface
It's also important to note that , It is not always necessary to 1:n, Disassemble the middle table 1:1, First of all, we need to predict , Whether what you are doing is similar to Multiple tables are associated , There are changes Is it possible to use in many places , Whether it belongs to a business model , Like pages and components , It's a 1:n The relationship between , Under a business model , Then there is no need to build a middle table of page components , Add a page directly to the component table id Just a field
6.0 If 2 There are... Between tables n:n The relationship between , This relationship should be eliminated instead
The way to eliminate it is , Add a third table between the two . such , original n:n The relationship between , Now it's two 1:n The relationship between . To put The attributes of the original two tables are reasonably allocated To the first 3 A watch . In general , Database design tools don't recognize many to many relationships , But can handle many to many relationships
For example “ Library Information System ” in ,“ The book ” Corresponding to a table ,“ readers ” It also corresponds to a table . The relationship between these two tables , It's a typical many to many relationship , A book can be borrowed by multiple readers at different times , A reader can borrow more than one book , So , To add a third entity between the two , The entity is named “ Borrow and return books ”, Its property is : Borrowing and returning time 、 Loan return sign (0 To borrow a book ,1 To return a book ), in addition , It should also have two foreign keys (“ The book ” Primary key of ,“ readers ” Primary key of ), Make it compatible with “ The book ” and “ readers ” Connect
7.0 n:n The eliminated intermediate table is appropriately redundant with fields
The attributes of the original two tables are reasonably allocated The upper paragraph is bold Most of the time Everyone will put n:n Open , But it is not the middle table that comes out 3 A field , With the above books , Take readers for example , Suppose the middle table is 3 A field
CREATE TABLE `book_reader` (
`id` varchar(10) NOT NULL COMMENT ' Primary key number ',
`book_id` varchar(50) NOT NULL COMMENT 'book surface Primary key ',
`reader_id` varchar(10) DEFAULT NULL COMMENT ' Reader table primary key '
PRIMARY KEY (`region_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=' The book , The reader's middle table ';
Copy code This table is particularly in line with the three paradigms , But when you make a query, you have to associate it every time 3 Table query , In fact, some information can be appropriately redundant , Like the title of the book , Of the book isbn Number , The advantage of this is , Look up the middle table to get some information , But here's the thing To distribute reasonably , Don't put frequently changed fields in the middle table , When updating data , Remember to update the intermediate table
8.0 Last
Most of the time, we will not encounter very complex database operations and table structure design in the front end , Basically understood RBAC User rights management database design , Can meet all kinds of daily design ,RBAPC Model contains user , role , jurisdiction , menu , contain 1:n,n:n Relationship , It is worth studying hard
Reference material :
边栏推荐
- EasyClick 运行代码片段出Null
- Implementation of fruit mall wholesale platform based on SSM
- 架构师必备:系统容量现状checklist
- DNS协议分析
- MySQL monitoring tool PMM, let you go to a higher level (Part 2)
- Design of simple electronic clock based on single chip microcomputer
- 软件测试常问,你真的会搭建测试环境吗?
- 技术管理进阶——管理者可以使用哪些管理工具
- Pytorch basis (II) -- tensor and gradient
- 等个有“源”人|OpenHarmony 成长计划学生挑战赛报名启动
猜你喜欢

记一次水平越权漏洞的利用

Full stack development practice | integrated development of SSM framework

Brief introduction to memory structure of virtual machine

ThingsBoard教程(二十):使用规则链过滤遥测数据

SQL Server创建windows登录账户找不到用户或组

Actual combat simulation │ real time error alarm of enterprise wechat robot

Matplotlib learning notes

Information document management and configuration management

低代码开发一个基础模块

go-zero微服务实战系列(三、API定义和表结构设计)
随机推荐
Solution to qt5.12 unable to input Chinese (unable to switch Chinese input method) in deepin system
SQL Server创建windows登录账户找不到用户或组
Mobile web effects
Idea life extension plug-in
Vivo large scale kubernetes cluster automation operation and maintenance practice
[bearing fault decomposition] ITD bearing fault signal decomposition based on MATLAB [including Matlab source code 1871]
信息文档管理与配置管理
DNS协议分析
Introduction to recursive idea and implementation, eliminating recursion
vivo大规模 Kubernetes 集群自动化运维实践
Memory management -- Viewing memory space from the perspective of executing programs and processes
index查list 注入的是mysql 执行的是oracle
Docker部署Mysql
苹果放大招!这件事干的太漂亮了……
Mysql database conceptual design using E-R model
Win7 cannot be remote desktop problem
Oracle custom data type question
Thingsboard tutorial (21): save data after processing using message types and data processing nodes
基于SSM实现水果商城批发平台
QTcpServer. QTcpSocket. Differences between qudpsockets