Table of Contents p>
- 1. Specification background and purpose
- 2. Design specification
- 2.1. Database design
- 2.1.1. Library name
- 2.1.2. Table structure
- 2.1.3. Column data type optimization
- 2.1.4. Index design
- 2.1.5. Sub-database, sub-table, partition table
- 2.1.6. Character set
- 2.1.7. An example of a standardized table creation statement
li>
- 2.2. SQL writing
- 2.2.1. DML statement
- 2.2.2. Multi-table connection
- 2.2 .3. Transactions
- 2.2.4. Sorting and grouping
- 2.2.5. SQL statements prohibited online
ul>
- 2.1. Database design
1. Background and Purpose of Specification
The purpose of this specification is to help or guide RD , QA, OP and other technical personnel to make database design suitable for online business. Standardize database changes and processing procedures, database table design, SQL writing, etc., so as to provide guarantee for the stable and healthy operation of the company’s business system.
2. Design Specification
2.1. Database Design
-
All the following specifications It will be marked according to the three levels of [High Risk], [Mandatory], and [Recommended], and follow the priority from high to low.
-
For designs that do not meet the two levels of [High Risk] and [Mandatory], the DBA has the right to forcefully call back and modify it.
2.1.1. Library name
- [Mandatory] The name of the library must be controlled within 32 characters , The table name and table name of related modules reflect the join relationship as much as possible, such as user table and user_login table.
- [Mandatory] The name format of the library: business system name_subsystem name, and the library name used by the same module should use a uniform prefix as much as possible. _
- [Mandatory] The naming format of the general sub-library name is library wildcard name_number, and the number increases from 0. For example, the name format of wenda_001 to sub-library by time is “library wildcard name_time”
- [Mandatory] The character set must be explicitly specified when creating the database, and the character set can only be utf8 or utf8mb4. SQL example for creating a database:
create database db1 default character set utf8;
2.1.2. Table structure
- 【 Mandatory] The table must have a primary key, and set id as an auto-incrementing primary key.
- [Mandatory] Tables prohibit the use of foreign keys. If you want to ensure completeness, it should be implemented by the terminal. Foreign keys make the tables coupled with each other, affecting the performance of update, delete, etc., and may cause deadlock. High concurrency environment can easily lead to database performance bottlenecks.
- [Mandatory] Table and column names must be controlled within 32 characters. Table names can only use letters, numbers and underscores, all in lower case. If the table name is too long, abbreviations can be used.
- [Mandatory] When creating a table, you must explicitly specify the character set as utf8 or utf8mb4.
- [Mandatory] When creating a table, you must explicitly specify the table storage engine type. If there is no special requirement, it will be InnoDB. When a storage engine other than InnoDB/MyISAM/Memory needs to be used, it must be audited by the DBA before it can be used in a production environment. Because Innodb tables support important features of relational databases such as transactions, row locks, crash recovery, and MVCC, it is the most used MySQL storage engine in the industry. This is something that most other storage engines do not have, so InnoDB is the first choice.
- [Mandatory] There must be a comment to create a table, and both the table level and the field level must have comments.
- [Recommendation] Regarding the primary key when building a table: (1) Mandatory primary key is id, type is int or bigint (for future scalability, here requires new tables to be unified as bigint), and is auto_increment(2 ) Do not set the field of the main body of each row in the identification table as the primary key. It is recommended to set other fields such as user_id, order_id, etc., and establish a unique key index. Because if it is set as the primary key and the primary key value is randomly inserted, it will cause innodb internal page splitting and a large amount of random I/O, and performance will decrease.
- [Recommendation] Core tables (such as user tables, money-related tables) must have the creation time field create_time and the last update time field update_time of the row data, so that it is easy to check the problem.
- [Recommendation] All fields in the table must be NOT NULL default default value attributes, and the business can define the DEFAULT value as needed. Because the use of NULL values will have problems such as each row will occupy additional storage space, data migration is prone to errors, aggregate function calculation results deviation, and index failure.
- [Suggestion] It is recommended to split the large fields such as blob and text in the table into other tables vertically, and select only when you need to read these objects
- 【Suggestion 】Anti-paradigm design: Make redundant copies of fields that often need to be joined in other tables. For example, the user_name attribute is redundant in the user_account, user_login_log and other tables to reduce join queries.
- [Mandatory] The intermediate table is used to retain the intermediate result set, and the name must start with tmp_. The backup table is used to back up or grab a snapshot of the source table. The name must start with bak_. Intermediate tables and backup tables are cleaned up regularly.
- [Mandatory] For online implementation of DDL changes, it must be reviewed by the DBA and executed by the DBA during the low peak period of the business.
2.1.3. Column data type optimization
- [Recommendation] Auto-increment column in the table (auto_increment attribute) , It is recommended to use the bigint type. Because the storage range of unsigned int is -2147483648~2147483647 (about 2.1 billion), an error will be reported after overflow.
- [Recommendation] For fields such as status and type with few options in the business, it is recommended to use tinytint or smallint to save storage space.
- [Recommendation] The int type is recommended for the IP address field in the business, and char(15) is not recommended. Because int only occupies 4 bytes, you can use the following functions to convert each other, and char(15) occupies at least 15 bytes. Once the number of table data rows reaches 100 million, 1.1G more storage space is needed. SQL: select inet_aton(‘192.168.2.12’); select inet_ntoa(3232236044); PHP: ip2long(‘192.168.2.12’); long2ip(3530427185);
- [Recommendation] Enum, set is not recommended . Because they waste space, and the enumeration value is hard-coded, it is inconvenient to change. It is recommended to use tinyint or smallint.
- [Recommendation] Blob, text and other types are not recommended. They all waste hard disk and memory space. When loading table data, large fields are read into memory, which wastes memory space and affects system performance. It is recommended to communicate with PM and RD whether such a large field is really needed.
- [Recommendation] The field for storing money, it is recommended to use int, the terminal multiplies by 100 and divides by 100 for access. Or use decimal type instead of double.
- [Recommendation] Use varchar to store text data as much as possible. Because varchar is a variable-length storage, it saves more space than char. The MySQL server layer stipulates that all text in a line can store up to 65535 bytes.
- [Recommendation] Try to select datetime as the time type. Although timestamp occupies less space, there is a problem that the time range is from 1970-01-01 00:00:01 to 2038-01-01 00:00:00.
2.1.4. Index Design
- [Mandatory] InnoDB tables must have the primary key id int/bigint auto_increment, and the primary key The value must not be updated.
- [Recommendation] The unique key starts with “uk_” or “uq_”, and the common index starts with “idx_”. All lowercase format is used, with the field name or abbreviation as the suffix.
- [Mandatory] InnoDB and MyISAM storage engine tables, the index type must be BTREE; MEMORY table can choose HASH or BTREE type index as needed.
- [Mandatory] The length of each index record in a single index cannot exceed 64KB.
- [Recommendation] The number of indexes on a single table cannot exceed 5.
- [Recommendation] When creating an index, consider building a joint index, and put the most distinguished field at the top. For example, the distinction of column userid can be calculated by select count (distinct userid).
- [Recommendation] In the SQL of a multi-table join, ensure that there is an index on the join column of the driven table, so that the join execution efficiency is the highest.
- [Recommendation] When building tables or adding indexes, ensure that there are no redundant indexes in the tables. For MySQL, if key(a,b) already exists in the table, key(a) is a redundant index and needs to be deleted.
2.1.5. Sub-database, sub-table, partition table
- [Mandatory] Partition field of the partition table (Partition-key) must have an index, or be the first column of a composite index.
- [Mandatory] The number of partitions (including subpartitions) in a single partition table cannot exceed 1024.
- [Mandatory] Before going online, RD or DBA must specify the partition table creation and cleanup strategy.
- [Mandatory] The SQL used to access the partition table must contain the partition key.
- [Recommendation] A single partition file should not exceed 2G, and the total size should not exceed 50G. It is recommended that the total number of partitions does not exceed 20.
- 【Mandatory】Alter table operation for partition table must be executed during low peak period of business.
- [Mandatory] The number of libraries cannot exceed 1024 if the database is divided into a strategy
- [Mandatory] If the strategy is adopted, the number of tables cannot exceed 4096
- [Recommendation] It is recommended that a single sub-table does not exceed 500W rows, so as to ensure better data query performance.
- [Recommendation] Try to use modulo as much as possible for the horizontal sub-table, and reserve enough buffer to avoid the need to re-split and migrate in the future. It is recommended to use the date for log and report data.
2.1.6. Character Set
- [Mandatory] All character sets of the database itself, tables, and columns must be consistent. It is utf8 or utf8mb4.
- [Mandatory] The character set of the front-end program or the character set in the environment variable must be consistent with the character set of the database and table, unified to utf8.
2.1.7. An example of a standardized table-building statement
A more standardized table-building statement is:< /p>
CREATE TABLE user (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) NOT NULL default ‘0’ COMMENT ‘userid’
`username` varchar(45) NOT NULL default ‘’ COMMENT ‘real name’,
`email` varchar(30) NOT NULL default ‘’COMMENT ‘user mailbox’,
`nickname` varchar(45) NOT NULL default ‘’ COMMENT ‘nickname’,
`avatar` int(11) NOT NULL default ‘0’ COMMENT ‘avatar’,
`birthday` date NOT NULL default ‘0000-00-00’ COMMENT ‘birthday’,
`sex` tinyint(4) not null DEFAULT ‘0‘ COMMENT ‘sex’,
`short_introduce` varchar(150) not null DEFAULT ‘’COMMENT ‘Introduce yourself in one sentence, up to 50 Chinese characters’,
`user_resume` varchar(200) NOT NULL default ‘’COMMENT ‘the storage address of the resume submitted by the user’,
`user_register_ip` int NOT NULL COMMENT ‘source ip when user registered’,
`create_time` datetime NOT NULL default current_timestamp COMMENT ‘the time when the user record was created’,
`update_time` datetime default current_timestamp on update current_timestamp NOT NULL COMMENT ‘the time of user information modification’,
`user_review_status` tinyint NOT NULL default ‘1’ COMMENT ‘user profile review status, 1 is passed, 2 is under review, 3 is not passed, 4 is not yet submitted for review’,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_user_id` (`user_id`),
KEY `idx_username`(`username`),
KEY `idx_create_time`(`create_time`,`user_review_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Basic information of website users';
2.2. SQL writing; h2>
2.2.1. DML statement
- [Mandatory] The SELECT statement must specify the specific field name, and it is forbidden to write it as . Because select will also read data that should not be read from MySQL, causing pressure on the network card. And once the table fields are updated, but the terminal does not have time to update, the system will report an error.
- [Mandatory] The insert statement specifies the specific field name, do not write insert into t1 values(…), the same is true.
- [Suggestion] insert into…values(XX),(XX),(XX)…. The value of XX here should not exceed 500. Too many values, although the online is very fast, but will cause the master-slave synchronization delay.
- [Recommendation] Do not use UNION in the SELECT statement, it is recommended to use UNION ALL, and the number of UNION clauses is limited to 3 or less. Because union all does not need to be deduplicated, it saves database resources and improves performance.
- [Recommendation] The in value list is limited to 500. For example, select… where userid in (…500 within…). This is done to reduce the underlying scanning, reduce the pressure on the database and speed up the query.
- [Suggestion] To update the data in batches in the transaction, you need to control the amount, and do the necessary sleep, and do it in small amounts and multiple times.
- [Mandatory] All tables involved in the transaction must be innodb tables. Otherwise, once it fails, it will not all roll back, and it will easily cause the synchronization of the master and slave libraries to be interrupted.
- [Mandatory] Writes and transactions are sent to the main library, and read-only SQL is sent to the slave library, that is, the terminal realizes read-write separation.
- [Mandatory] DML statements must have where conditions and use index search.
- [Mandatory] Hints are prohibited in the production environment, such as sql_no_cache, force index, ignore key, straight join, etc. Because hint is used to force SQL to execute according to a certain execution plan, but as the amount of data changes, we cannot guarantee that our original prediction is correct. We should try our best to let the MySQL optimizer choose the execution plan by itself.
- [Mandatory] The field types of the left and right equal signs in the where condition must be the same, otherwise the index cannot be used.
- [Recommendation] SELECT|UPDATE|DELETE|REPLACE must have a WHERE clause, and the conditions of the WHERE clause must be searched by index.
- [Mandatory] It is strongly not recommended that a full table scan occurs on large tables in a production database, but a full table scan can be used for static tables with less than 100 rows. The query data volume should not exceed 25% of the number of table rows, otherwise the index will not be used.
- [Mandatory] In the WHERE clause, it is forbidden to use only the fuzzy LIKE condition for searching. If you want to use like, please use the like’xxxx%’ method. There must be other equivalent or range query conditions. Otherwise, the index cannot be used.
- [Recommendation] Do not use functions or expressions in the index column, otherwise the index cannot be used. Such as where length(name)=‘Admin’ or where user_id+2=10023.
- [Recommendation] Reduce the use of or statements, optimize the or statements to union, and then build indexes on each where condition. For example, where a=1 or b=2 is optimized to where a=1…union…where b=2, key(a), key(b).
- [Recommendation] Paging query, when the limit starting point is high, you can use the filter criteria to filter first. For example, select a,b,c from t1 limit 10000,20; optimized to: select a,b,c from t1 where id>10000 limit 20;.
2.2.2. Multi-table join
- [Mandatory] Cross-db join statement is prohibited. Because this can reduce the coupling between modules and lay a solid foundation for database splitting.
- [Mandatory] It is forbidden to use join in business update SQL statements, such as update t1 join t2…
- [Recommendation] It is not recommended to use sub-queries. It is recommended to split the sub-query SQL and combine the program for multiple queries, or use join instead of sub-queries.
- [Recommendation] For online environment, multi-table join should not exceed 3 tables.
- [Recommendation] It is recommended to use aliases for multi-table join queries, and aliases should be used to reference fields in the SELECT list, database. Table format, such as select a from db1.table1 alias1 where ….
- [Recommendation] In a multi-table join, try to select the table with the smaller result set as the driving table to join other tables.
2.2.3. Transactions
- [Recommendation] The number of rows operated by the INSERT|UPDATE|DELETE|REPLACE statement in the transaction is controlled within Within 1000, and the number of parameters passed in the IN list in the WHERE clause is controlled within 500.
- [Suggestion] When operating data in batches, you need to control the transaction processing interval and perform necessary sleep. Generally, the recommended value is 1-2 seconds.
- [Recommendation] For insert operations into tables with auto_increment attribute fields, the concurrency needs to be controlled within 200.
- [Mandatory] Program design must consider the impact of “database transaction isolation level”, including dirty reads, non-repeatable reads, and phantom reads. The online recommended transaction isolation level is repeatable-read.
- [Recommendation] The transaction contains no more than 5 SQL (except payment services). Because too long a transaction will lead to a long time lock data, MySQL internal cache, connection consumption and other avalanche problems.
- [Recommendation] The update statement in the transaction should be based on the primary key or unique key as much as possible, such as update… where id=XX; Otherwise, a gap lock will be generated, and the lock range will be expanded internally, resulting in system performance degradation and deadlock.
- [Recommendation] Try to move some typical external calls out of the transaction, such as calling webservice, accessing file storage, etc., so as to avoid the transaction from being too long.
[Suggestion] For select statements that are strictly sensitive to the MySQL master-slave delay, please enable transactions to force access to the master database.
2.2.4. Sorting and grouping
- [Recommendation] Reduce the use of order by, and communicate with business without sorting Do not sort, or put the sort in the terminal to do it. Statements such as order by, group by, and distinct consume more CPU, and the CPU resources of the database are extremely precious.
- 【Suggestion】Order by, group by, distinct SQL try to use the index to directly retrieve the sorted data. For example, where a=1 order by can use key(a,b).
- [Suggestion] Contains query statements such as order by, group by, distinct, and the result set filtered by the where condition should be kept within 1000 rows, otherwise the SQL will be very slow.
2.2.5. SQL statements prohibited online
- [High Risk] Disable update|delete t1… where a=XX limit XX; This kind of update statement with limit. If it is a binlog format other than row format, it will lead to inconsistency between master and slave, resulting in data confusion. It is recommended to add order by PK.
- [High Risk] It is forbidden to use associated sub-queries, such as update t1 set… where name in(select name from user where…); The efficiency is extremely low.
- [Mandatory] Disable procedure, function, trigger, views, event, and foreign key constraints. Because they consume database resources, reduce the scalability of the database instance. Recommendations are implemented in the terminal.
- [Recommendation] Disable insert into …on duplicate key update…, replace into and other statements. In a high concurrency environment, it is very easy to cause deadlock.
- [Mandatory] It is forbidden to join table update statements, such as update t1, t2 where t1.id=t2.id…
[Suggestion] For select statements that are strictly sensitive to the MySQL master-slave delay, please enable transactions to force access to the master database.
Table of Contents
- 1. Standardize the background and purpose
- 2 . Design specification
- 2.1. Database design
- 2.1.1. Library name
- 2.1.2. Table structure
- 2.1.3. Column Data type optimization
- 2.1.4. Index design
- 2.1.5. Sub-database, sub-table, partition table
- 2.1.6. Character set
- 2.1.7. A standard example of table creation statement
- 2.2. SQL writing
- 2.2.1. DML statement
- 2.2.2. Multi-table connection
- 2.2.3. Transactions
- 2.2.4. Sorting and grouping
- 2.2.5. Online prohibition The SQL statement used
- 2.1. Database design
1. Specification Background and purpose
This specification aims to help or guide RD, QA, OP and other technical personnel to make database design suitable for online business. Standardize database changes and processing procedures, database table design, SQL writing, etc., so as to provide guarantee for the stable and healthy operation of the company’s business system.
2. Design Specification
2.1. Database Design
-
All the following specifications It will be marked according to the three levels of [High Risk], [Mandatory], and [Recommended], and follow the priority from high to low.
-
For designs that do not meet the two levels of [High Risk] and [Mandatory], the DBA has the right to forcefully call back and modify it.
2.1.1. Library name
- [Mandatory] The name of the library must be controlled within 32 characters , The table name and table name of related modules reflect the join relationship as much as possible, such as user table and user_login table.
- [Mandatory] The name format of the library: business system name_subsystem name, and the library name used by the same module should use a uniform prefix as much as possible. _
- [Mandatory] The naming format of the general sub-library name is library wildcard name_number, and the number increases from 0. For example, the name format of wenda_001 to sub-library by time is “library wildcard name_time”
- [Mandatory] The character set must be explicitly specified when creating the database, and the character set can only be utf8 or utf8mb4. SQL example for creating a database:
create database db1 default character set utf8;
2.1.2. Table structure
- 【 Mandatory] The table must have a primary key, and set id as an auto-incrementing primary key.
- [Mandatory] Tables prohibit the use of foreign keys. If you want to ensure completeness, it should be implemented by the terminal. Foreign keys make the tables coupled with each other, affecting the performance of update, delete, etc., and may cause deadlock. High concurrency environment can easily lead to database performance bottlenecks.
- [Mandatory] Table and column names must be controlled within 32 characters. Table names can only use letters, numbers and underscores, all in lower case. If the table name is too long, abbreviations can be used.
- [Mandatory] When creating a table, you must explicitly specify the character set as utf8 or utf8mb4.
- [Mandatory] When creating a table, you must explicitly specify the table storage engine type. If there is no special requirement, it will be InnoDB. When a storage engine other than InnoDB/MyISAM/Memory needs to be used, it must be audited by the DBA before it can be used in a production environment. Because Innodb tables support important features of relational databases such as transactions, row locks, crash recovery, and MVCC, it is the most used MySQL storage engine in the industry. This is something that most other storage engines do not have, so InnoDB is the first choice.
- [Mandatory] There must be a comment to create a table, and both the table level and the field level must have comments.
- [Recommendation] Regarding the primary key when building a table: (1) Mandatory primary key is id, type is int or bigint (for future scalability, here requires new tables to be unified as bigint), and is auto_increment(2 ) Do not set the field of the main body of each row in the identification table as the primary key. It is recommended to set other fields such as user_id, order_id, etc., and establish a unique key index. Because if it is set as the primary key and the primary key value is randomly inserted, it will cause innodb internal page splitting and a large amount of random I/O, and performance will decrease.
- [Recommendation] Core tables (such as user tables, money-related tables) must have the creation time field create_time and the last update time field update_time of the row data, so that it is easy to check the problem.
- [Recommendation] All fields in the table must be NOT NULL default default value attributes, and the business can define the DEFAULT value as needed. Because the use of NULL values will have problems such as each row will occupy additional storage space, data migration is prone to errors, aggregate function calculation results deviation, and index failure.
- [Suggestion] It is recommended to split the large fields such as blob and text in the table into other tables vertically, and select only when you need to read these objects
- 【Suggestion 】Anti-paradigm design: Make redundant copies of fields that often need to be joined in other tables. For example, the user_name attribute is redundant in the user_account, user_login_log and other tables to reduce join queries.
- [Mandatory] The intermediate table is used to retain the intermediate result set, and the name must start with tmp_. The backup table is used to back up or grab a snapshot of the source table. The name must start with bak_. Intermediate tables and backup tables are cleaned up regularly.
- [Mandatory] For online implementation of DDL changes, it must be reviewed by the DBA and executed by the DBA during the low peak period of the business.
2.1.3. Column data type optimization
- [Recommendation] Auto-increment column in the table (auto_increment attribute) , It is recommended to use the bigint type. Because the storage range of unsigned int is -2147483648~2147483647 (about 2.1 billion), an error will be reported after overflow.
- [Recommendation] For fields such as status and type with few options in the business, it is recommended to use tinytint or smallint to save storage space.
- [Recommendation] The int type is recommended for the IP address field in the business, and char(15) is not recommended. Because int only occupies 4 bytes, you can use the following functions to convert each other, and char(15) occupies at least 15 bytes. Once the number of table data rows reaches 100 million, 1.1G more storage space is needed. SQL: select inet_aton(‘192.168.2.12’); select inet_ntoa(3232236044); PHP: ip2long(‘192.168.2.12’); long2ip(3530427185);
- [Recommendation] Enum, set is not recommended . Because they waste space, and the enumeration value is hard-coded, it is inconvenient to change. It is recommended to use tinyint or smallint.
- [Recommendation] Blob, text and other types are not recommended. They all waste hard disk and memory space. When loading table data, large fields are read into memory, which wastes memory space and affects system performance. It is recommended to communicate with PM and RD whether such a large field is really needed.
- [Recommendation] The field for storing money, it is recommended to use int, the terminal multiplies by 100 and divides by 100 for access. Or use decimal type instead of double.
- [Recommendation] Use varchar to store text data as much as possible. Because varchar is a variable-length storage, it saves more space than char. The MySQL server layer stipulates that all text in a line can store up to 65535 bytes.
- [Recommendation] Try to select datetime as the time type. Although timestamp occupies less space, there is a problem that the time range is from 1970-01-01 00:00:01 to 2038-01-01 00:00:00.
2.1.4. Index Design
- [Mandatory] InnoDB tables must have the primary key id int/bigint auto_increment, and the primary key The value must not be updated.
- [Recommendation] The unique key starts with “uk_” or “uq_”, and the common index starts with “idx_”. All lowercase format is used, with the field name or abbreviation as the suffix.
- [Mandatory] InnoDB and MyISAM storage engine tables, the index type must be BTREE; MEMORY table can choose HASH or BTREE type index as needed.
- [Mandatory] The length of each index record in a single index cannot exceed 64KB.
- [Recommendation] The number of indexes on a single table cannot exceed 5.
- [Recommendation] When creating an index, consider building a joint index, and put the most distinguished field at the top. For example, the distinction of column userid can be calculated by select count (distinct userid).
- [Recommendation] In the SQL of a multi-table join, ensure that there is an index on the join column of the driven table, so that the join execution efficiency is the highest.
- [Recommendation] When building tables or adding indexes, ensure that there are no redundant indexes in the tables. For MySQL, if key(a,b) already exists in the table, key(a) is a redundant index and needs to be deleted.
2.1.5. Sub-database, sub-table, partition table
- [Mandatory] Partition field of the partition table (Partition-key) must have an index, or be the first column of a composite index.
- [Mandatory] The number of partitions (including subpartitions) in a single partition table cannot exceed 1024.
- [Mandatory] Before going online, RD or DBA must specify the partition table creation and cleanup strategy.
- [Mandatory] The SQL used to access the partition table must contain the partition key.
- [Recommendation] A single partition file should not exceed 2G, and the total size should not exceed 50G. It is recommended that the total number of partitions does not exceed 20.
- 【Mandatory】Alter table operation for partition table must be executed during low peak period of business.
- [Mandatory] The number of libraries cannot exceed 1024 if the database is divided into a strategy
- [Mandatory] If the strategy is adopted, the number of tables cannot exceed 4096
- [Recommendation] It is recommended that a single sub-table does not exceed 500W rows, so as to ensure better data query performance.
- [Recommendation] Try to use modulo as much as possible for the horizontal sub-table, and reserve enough buffer to avoid the need to re-split and migrate in the future. It is recommended to use the date for log and report data.
2.1.6. Character Set
- [Mandatory] All character sets of the database itself, tables, and columns must be consistent. It is utf8 or utf8mb4.
- [Mandatory] The character set of the front-end program or the character set in the environment variable must be consistent with the character set of the database and table, unified to utf8.
2.1.7. An example of a standardized table-building statement
A more standardized table-building statement is:< /p>
CREATE TABLE user (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) NOT NULL default ‘0’ COMMENT ‘userid’
`username` varchar(45) NOT NULL default ‘’ COMMENT ‘real name’,
`email` varchar(30) NOT NULL default ‘’COMMENT ‘user mailbox’,
`nickname` varchar(45) NOT NULL default ‘’ COMMENT ‘nickname’,
`avatar` int(11) NOT NULL default ‘0’ COMMENT ‘avatar’,
`birthday` date NOT NULL default ‘0000-00-00’ COMMENT ‘birthday’,
`sex` tinyint(4) not null DEFAULT ‘0‘ COMMENT ‘sex’,
`short_introduce` varchar(150) not null DEFAULT ‘’COMMENT ‘Introduce yourself in one sentence, up to 50 Chinese characters’,
`user_resume` varchar(200) NOT NULL default ‘’COMMENT ‘the storage address of the resume submitted by the user’,
`user_register_ip` int NOT NULL COMMENT ‘source ip when user registered’,
`create_time` datetime NOT NULL default current_timestamp COMMENT ‘the time when the user record was created’,
`update_time` datetime default current_timestamp on update current_timestamp NOT NULL COMMENT ‘the time of user information modification’,
`user_review_status` tinyint NOT NULL default ‘1’ COMMENT ‘user profile review status, 1 is passed, 2 is under review, 3 is not passed, 4 is not yet submitted for review’,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_user_id` (`user_id`),
KEY `idx_username`(`username`),
KEY `idx_create_time`(`create_time`,`user_review_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Basic information of website users';
2.2. SQL writing; h2>
2.2.1. DML statement
- [Mandatory] The SELECT statement must specify the specific field name, and it is forbidden to write it as . Because select will also read data that should not be read from MySQL, causing pressure on the network card. And once the table fields are updated, but the terminal does not have time to update, the system will report an error.
- [Mandatory] The insert statement specifies the specific field name, do not write insert into t1 values(…), the same is true.
- [Suggestion] insert into…values(XX),(XX),(XX)…. The value of XX here should not exceed 500. Too many values, although the online is very fast, but will cause the master-slave synchronization delay.
- [Recommendation] Do not use UNION in the SELECT statement, it is recommended to use UNION ALL, and the number of UNION clauses is limited to 3 or less. Because union all does not need to be deduplicated, it saves database resources and improves performance.
- [Recommendation] The in value list is limited to 500. For example, select… where userid in (…500 within…). This is done to reduce the underlying scanning, reduce the pressure on the database and speed up the query.
- [Suggestion] To update the data in batches in the transaction, you need to control the amount, and do the necessary sleep, and do it in small amounts and multiple times.
- [Mandatory] All tables involved in the transaction must be innodb tables. Otherwise, once it fails, it will not all roll back, and it will easily cause the synchronization of the master and slave libraries to be interrupted.
- 【强制】写入和事务发往主库,只读SQL发往从库,即程序端实现读写分离。
- 【强制】DML语句必须有where条件,且使用索引查找。
- 【强制】生产环境禁止使用hint,如sql_no_cache,force index,ignore key,straight join等。因为hint是用来强制SQL按照某个执行计划来执行,但随着数据量变化我们无法保证自己当初的预判是正确的,我们要尽量让MySQL优化器自己选择执行计划。
- 【强制】where条件里等号左右字段类型必须一致,否则无法利用索引。
- 【建议】SELECT|UPDATE|DELETE|REPLACE要有WHERE子句,且WHERE子句的条件必需使用索引查找。
- 【强制】生产数据库中强烈不推荐大表上发生全表扫描,但对于100行以下的静态表可以全表扫描。查询数据量不要超过表行数的25%,否则不会利用索引。
- 【强制】WHERE 子句中禁止只使用全模糊的LIKE条件进行查找,如果要使用like,请使用like ‘xxxx%’的方式,必须有其他等值或范围查询条件,否则无法利用索引。
- 【建议】索引列不要使用函数或表达式,否则无法利用索引。如where length(name)=‘Admin‘或where user_id+2=10023。
- 【建议】减少使用or语句,可将or语句优化为union,然后在各个where条件上建立索引。如where a=1 or b=2优化为where a=1… union …where b=2, key(a),key(b)。
- 【建议】分页查询,当limit起点较高时,可先用过滤条件进行过滤。如select a,b,c from t1 limit 10000,20;优化为: select a,b,c from t1 where id>10000 limit 20;。
2.2.2. 多表连接
- 【强制】禁止跨db的join语句。因为这样可以减少模块间耦合,为数据库拆分奠定坚实基础。
- 【强制】禁止在业务的更新类SQL语句中使用join,比如update t1 join t2…。
- 【建议】不建议使用子查询,建议将子查询SQL拆开结合程序多次查询,或使用join来代替子查询。
- 【建议】线上环境,多表join不要超过3个表。
- 【建议】多表连接查询推荐使用别名,且SELECT列表中要用别名引用字段,数据库.表格式,如select a from db1.table1 alias1 where …。
- 【建议】在多表join中,尽量选取结果集较小的表作为驱动表,来join其他表。
2.2.3. 事务
- 【建议】事务中INSERT|UPDATE|DELETE|REPLACE语句操作的行数控制在1000以内,以及WHERE子句中IN列表的传参个数控制在500以内。
- 【建议】批量操作数据时,需要控制事务处理间隔时间,进行必要的sleep,一般建议值1-2秒。
- 【建议】对于有auto_increment属性字段的表的插入操作,并发需要控制在200以内。
- 【强制】程序设计必须考虑“数据库事务隔离级别”带来的影响,包括脏读、不可重复读和幻读。线上建议事务隔离级别为repeatable-read。
- 【建议】事务里包含SQL不超过5个(支付业务除外)。因为过长的事务会导致锁数据较久,MySQL内部缓存、连接消耗过多等雪崩问题。
- 【建议】事务里更新语句尽量基于主键或unique key,如update … where id=XX; 否则会产生间隙锁,内部扩大锁定范围,导致系统性能下降,产生死锁。
- 【建议】尽量把一些典型外部调用移出事务,如调用webservice,访问文件存储等,从而避免事务过长。
【建议】对于MySQL主从延迟严格敏感的select语句,请开启事务强制访问主库。
2.2.4. 排序和分组
- 【建议】减少使用order by,和业务沟通能不排序就不排序,或将排序放到程序端去做。 order by、group by、distinct这些语句较为耗费CPU,数据库的CPU资源是极其宝贵的。
- 【建议】order by、group by、distinct这些SQL尽量利用索引直接检索出排序好的数据。如where a=1 order by可以利用key(a,b)。
- 【建议】包含了order by、group by、distinct这些查询的语句,where条件过滤出来的结果集请保持在1000行以内,否则SQL会很慢。
2.2.5. 线上禁止使用的SQL语句
- 【高危】禁用update|delete t1 … where a=XX limit XX; 这种带limit的更新语句。如果是非row格式的binlog格式,会导致主从不一致,导致数据错乱。建议加上order by PK。
- 【高危】禁止使用关联子查询,如update t1 set … where name in(select name from user where…);效率极其低下。
- 【强制】禁用procedure、function、trigger、views、event、外键约束。因为他们消耗数据库资源,降低数据库实例可扩展性。推荐都在程序端实现。
- 【建议】禁用insert into …on duplicate key update…、replace into等语句,在高并发环境下,极容易导致死锁。
- 【强制】禁止联表更新语句,如update t1,t2 where t1.id=t2.id…。
【建议】对于MySQL主从延迟严格敏感的select语句,请开启事务强制访问主库。
目录
- 1. 规范背景与目的
- 2. 设计规范
- 2.1. 数据库设计
- 2.1.1. 库名
- 2.1.2. 表结构
- 2.1.3. 列数据类型优化
- 2.1.4. 索引设计
- 2.1.5. 分库分表、分区表
- 2.1.6. 字符集
- 2.1.7. 一个规范的建表语句示例
- 2.2. SQL编写
- 2.2.1. DML语句
- 2.2.2. 多表连接
- 2.2.3. 事务
- 2.2.4. 排序和分组
- 2.2.5. 线上禁止使用的SQL语句
- 2.1. 数据库设计
1. 规范背景与目的
本规范旨在帮助或指导RD、QA、OP等技术人员做出适合线上业务的数据库设计。在数据库变更和处理流程、数据库表设计、SQL编写等方面予以规范,从而为公司业务系统稳定、健康地运行提供保障。
2. 设计规范
2.1. 数据库设计
-
以下所有规范会按照【高危】、【强制】、【建议】三个级别进行标注,遵守优先级从高到低。
-
对于不满足【高危】和【强制】两个级别的设计,DBA有权利强制打回要求修改。
2.1.1. 库名
- 【强制】库的名称必须控制在32个字符以内,相关模块的表名与表名之间尽量体现join的关系,如user表和user_login表。
- 【强制】库的名称格式:业务系统名称_子系统名,同一模块使用的库名尽量使用统一前缀。 _
- 【强制】一般分库名称命名格式是库通配名_编号,编号从0开始递增,比如wenda_001以时间进行分库的名称格式是“库通配名_时间”
- 【强制】创建数据库时必须显式指定字符集,并且字符集只能是utf8或者utf8mb4。创建数据库SQL举例:
create database db1 default character set utf8;
2.1.2. 表结构
- 【强制】表必须有主键,且设置id为自增主键。
- 【强制】表禁止使用外键,如果要保证完整下,应由程序端实现,外键使表之间相互耦合,影响update、delete等性能,有可能造成死锁,高并发环境下容易导致数据库性能瓶颈。
- 【强制】表和列的名称必须控制在32个字符以内,表名只能使用字母、数字和下划线,一律小写。如表名过长可以采用缩写等方式。
- 【强制】创建表时必须显式指定字符集为utf8或utf8mb4。
- 【强制】创建表时必须显式指定表存储引擎类型,如无特殊需求,一律为InnoDB。当需要使用除InnoDB/MyISAM/Memory以外的存储引擎时,必须通过DBA审核才能在生产环境中使用。因为Innodb表支持事务、行锁、宕机恢复、MVCC等关系型数据库重要特性,为业界使用最多的MySQL存储引擎。而这是其他大多数存储引擎不具备的,因此首推InnoDB。
- 【强制】建表必须有comment,表级别和字段级别都要有comment。
- 【建议】建表时关于主键:(1)强制要求主键为id,类型为int或bigint(为了以后延展性,这里要求新建表统一为bigint),且为auto_increment(2)标识表里每一行主体的字段不要设为主键,建议设为其他字段如user_id,order_id等,并建立unique key索引。因为如果设为主键且主键值为随机插入,则会导致innodb内部page分裂和大量随机I/O,性能下降。
- 【建议】核心表(如用户表,金钱相关的表)必须有行数据的创建时间字段create_time和最后更新时间字段update_time,便于查问题。
- 【建议】表中所有字段必须都是NOT NULL default 默认值 属性,业务可以根据需要定义DEFAULT值。因为使用NULL值会存在每一行都会占用额外存储空间、数据迁移容易出错、聚合函数计算结果偏差以及索引失效等问题。
- 【建议】建议对表里的blob、text等大字段,垂直拆分到其他表里,仅在需要读这些对象的时候才去select
- 【建议】反范式设计:把经常需要join查询的字段,在其他表里冗余一份。如user_name属性在user_account,user_login_log等表里冗余一份,减少join查询。
- 【强制】中间表用于保留中间结果集,名称必须以tmp_开头。备份表用于备份或抓取源表快照,名称必须以bak_开头。中间表和备份表定期清理。
- 【强制】对于线上执行DDL变更,必须经过DBA审核,并由DBA在业务低峰期执行。
2.1.3. 列数据类型优化
- 【建议】表中的自增列(auto_increment属性),推荐使用bigint类型。因为无符号int存储范围为-2147483648~2147483647(大约21亿左右),溢出后会导致报错。
- 【建议】业务中选择性很少的状态status、类型type等字段推荐使用tinytint或者smallint类型节省存储空。
- 【建议】业务中IP地址字段推荐使用int类型,不推荐用char(15)。因为int只占4字节,可以用如下函数相互转换,而char(15)占用至少15字节。一旦表数据行数到了1亿,那么要多用1.1G存储空间。 SQL:select inet_aton(‘192.168.2.12‘); select inet_ntoa(3232236044); PHP: ip2long(‘192.168.2.12’); long2ip(3530427185);
- 【建议】不推荐使用enum,set。因为它们浪费空间,且枚举值写死了,变更不方便。推荐使用tinyint或smallint。
- 【建议】不推荐使用blob,text等类型。它们都比较浪费硬盘和内存空间。在加载表数据时,会读取大字段到内存里从而浪费内存空间,影响系统性能。建议和PM、RD沟通,是否真的需要这么大字段。
- 【建议】存储金钱的字段,建议用int,程序端乘以100和除以100进行存取。或者用decimal类型,而不要用double。
- 【建议】文本数据尽量用varchar存储。因为varchar是变长存储,比char更省空间。 MySQL server层规定一行所有文本最多存65535字节。
- 【建议】时间类型尽量选取datetime。而timestamp虽然占用空间少,但是有时间范围为1970-01-01 00:00:01到2038-01-01 00:00:00的问题。
2.1.4. 索引设计
- 【强制】InnoDB表必须主键为id int/bigint auto_increment,且主键值禁止被更新。
- 【建议】唯一键以“uk_”或“uq_”开头,普通索引以“idx_”开头,一律使用小写格式,以字段的名称或缩写作为后缀。
- 【强制】InnoDB和MyISAM存储引擎表,索引类型必须为BTREE;MEMORY表可以根据需要选择HASH或者BTREE类型索引。
- 【强制】单个索引中每个索引记录的长度不能超过64KB。
- 【建议】单个表上的索引个数不能超过5个。
- 【建议】在建立索引时,多考虑建立联合索引,并把区分度最高的字段放在最前面。如列userid的区分度可由select count(distinct userid)计算出来。
- 【建议】在多表join的SQL里,保证被驱动表的连接列上有索引,这样join执行效率最高。
- 【建议】建表或加索引时,保证表里互相不存在冗余索引。对于MySQL来说,如果表里已经存在key(a,b),则key(a)为冗余索引,需要删除。
2.1.5. 分库分表、分区表
- 【强制】分区表的分区字段(partition-key)必须有索引,或者是组合索引的首列。
- 【强制】单个分区表中的分区(包括子分区)个数不能超过1024。
- 【强制】上线前RD或者DBA必须指定分区表的创建、清理策略。
- 【强制】访问分区表的SQL必须包含分区键。
- 【建议】单个分区文件不超过2G,总大小不超过50G。建议总分区数不超过20个。
- 【强制】对于分区表执行alter table操作,必须在业务低峰期执行。
- 【强制】采用分库策略的,库的数量不能超过1024
- 【强制】采用分表策略的,表的数量不能超过4096
- 【建议】单个分表建议不超过500W行,这样才能保证数据查询性能更佳。
- 【建议】水平分表尽量用取模方式,并预留出足够的buffer,以免日后需要重新拆分和迁移,日志、报表类数据建议采用日期进行分表。
2.1.6. 字符集
- 【强制】数据库本身库、表、列所有字符集必须保持一致,为utf8或utf8mb4。
- 【强制】前端程序字符集或者环境变量中的字符集,与数据库、表的字符集必须一致,统一为utf8。
2.1.7. 一个规范的建表语句示例
一个较为规范的建表语句为:
CREATE TABLE user (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) NOT NULL default ‘0’ COMMENT ‘用户id’
`username` varchar(45) NOT NULL default ‘’ COMMENT ‘真实姓名‘,
`email` varchar(30) NOT NULL default ‘’COMMENT ‘用户邮箱’,
`nickname` varchar(45) NOT NULL default ‘’ COMMENT ‘昵称‘,
`avatar` int(11) NOT NULL default ‘0’ COMMENT ‘头像‘,
`birthday` date NOT NULL default ‘0000-00-00’ COMMENT ‘生日‘,
`sex` tinyint(4) not null DEFAULT ‘0‘ COMMENT ‘性别‘,
`short_introduce` varchar(150) not null DEFAULT ‘’COMMENT ‘一句话介绍自己,最多50个汉字‘,
`user_resume` varchar(200) NOT NULL default ‘’COMMENT ‘用户提交的简历存放地址‘,
`user_register_ip` int NOT NULL COMMENT ‘用户注册时的源ip’,
`create_time` datetime NOT NULL default current_timestamp COMMENT ‘用户记录创建的时间’,
`update_time` datetime default current_timestamp on update current_timestamp NOT NULL COMMENT ‘用户资料修改的时间’,
`user_review_status` tinyint NOT NULL default ‘1’ COMMENT ‘用户资料审核状态,1为通过,2为审核中,3为未通过,4为还未提交审核’,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_user_id` (`user_id`),
KEY `idx_username`(`username`),
KEY `idx_create_time`(`create_time`,`user_review_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=‘网站用户基本信息‘;
2.2. SQL编写
2.2.1. DML语句
- 【强制】SELECT语句必须指定具体字段名称,禁止写成。因为select 会将不该读的数据也从MySQL里读出来,造成网卡压力。且表字段一旦更新,但程序端没有来得及更新的话,系统会报错。
- 【强制】insert语句指定具体字段名称,不要写成insert into t1 values(…),道理同上。
- 【建议】insert into…values(XX),(XX),(XX)…。这里XX的值不要超过500个。值过多虽然上线很很快,但会引起主从同步延迟。
- 【建议】SELECT语句不要使用UNION,推荐使用UNION ALL,并且UNION子句个数限制在3个以内。因为union all不需要去重,节省数据库资源,提高性能。
- 【建议】in值列表限制在500以内。例如select… where userid in(….500个以内…),这么做是为了减少底层扫描,减轻数据库压力从而加速查询。
- 【建议】事务里批量更新数据需要控制数量,进行必要的sleep,做到少量多次。
- 【强制】事务涉及的表必须全部是innodb表。否则一旦失败不会全部回滚,且易造成主从库同步中断。
- 【强制】写入和事务发往主库,只读SQL发往从库,即程序端实现读写分离。
- 【强制】DML语句必须有where条件,且使用索引查找。
- 【强制】生产环境禁止使用hint,如sql_no_cache,force index,ignore key,straight join等。因为hint是用来强制SQL按照某个执行计划来执行,但随着数据量变化我们无法保证自己当初的预判是正确的,我们要尽量让MySQL优化器自己选择执行计划。
- 【强制】where条件里等号左右字段类型必须一致,否则无法利用索引。
- 【建议】SELECT|UPDATE|DELETE|REPLACE要有WHERE子句,且WHERE子句的条件必需使用索引查找。
- 【强制】生产数据库中强烈不推荐大表上发生全表扫描,但对于100行以下的静态表可以全表扫描。查询数据量不要超过表行数的25%,否则不会利用索引。
- 【强制】WHERE 子句中禁止只使用全模糊的LIKE条件进行查找,如果要使用like,请使用like ‘xxxx%’的方式,必须有其他等值或范围查询条件,否则无法利用索引。
- 【建议】索引列不要使用函数或表达式,否则无法利用索引。如where length(name)=‘Admin‘或where user_id+2=10023。
- 【建议】减少使用or语句,可将or语句优化为union,然后在各个where条件上建立索引。如where a=1 or b=2优化为where a=1… union …where b=2, key(a),key(b)。
- 【建议】分页查询,当limit起点较高时,可先用过滤条件进行过滤。如select a,b,c from t1 limit 10000,20;优化为: select a,b,c from t1 where id>10000 limit 20;。
2.2.2. 多表连接
- 【强制】禁止跨db的join语句。因为这样可以减少模块间耦合,为数据库拆分奠定坚实基础。
- 【强制】禁止在业务的更新类SQL语句中使用join,比如update t1 join t2…。
- 【建议】不建议使用子查询,建议将子查询SQL拆开结合程序多次查询,或使用join来代替子查询。
- 【建议】线上环境,多表join不要超过3个表。
- 【建议】多表连接查询推荐使用别名,且SELECT列表中要用别名引用字段,数据库.表格式,如select a from db1.table1 alias1 where …。
- 【建议】在多表join中,尽量选取结果集较小的表作为驱动表,来join其他表。
2.2.3. 事务
- 【建议】事务中INSERT|UPDATE|DELETE|REPLACE语句操作的行数控制在1000以内,以及WHERE子句中IN列表的传参个数控制在500以内。
- 【建议】批量操作数据时,需要控制事务处理间隔时间,进行必要的sleep,一般建议值1-2秒。
- 【建议】对于有auto_increment属性字段的表的插入操作,并发需要控制在200以内。
- 【强制】程序设计必须考虑“数据库事务隔离级别”带来的影响,包括脏读、不可重复读和幻读。线上建议事务隔离级别为repeatable-read。
- 【建议】事务里包含SQL不超过5个(支付业务除外)。因为过长的事务会导致锁数据较久,MySQL内部缓存、连接消耗过多等雪崩问题。
- 【建议】事务里更新语句尽量基于主键或unique key,如update … where id=XX; 否则会产生间隙锁,内部扩大锁定范围,导致系统性能下降,产生死锁。
- 【建议】尽量把一些典型外部调用移出事务,如调用webservice,访问文件存储等,从而避免事务过长。
【建议】对于MySQL主从延迟严格敏感的select语句,请开启事务强制访问主库。
2.2.4. 排序和分组
- 【建议】减少使用order by,和业务沟通能不排序就不排序,或将排序放到程序端去做。order by、group by、distinct这些语句较为耗费CPU,数据库的CPU资源是极其宝贵的。
- 【建议】order by、group by、distinct这些SQL尽量利用索引直接检索出排序好的数据。如where a=1 order by可以利用key(a,b)。
- 【建议】包含了order by、group by、distinct这些查询的语句,where条件过滤出来的结果集请保持在1000行以内,否则SQL会很慢。
2.2.5. 线上禁止使用的SQL语句
- 【高危】禁用update|delete t1 … where a=XX limit XX; 这种带limit的更新语句。如果是非row格式的binlog格式,会导致主从不一致,导致数据错乱。建议加上order by PK。
- 【高危】禁止使用关联子查询,如update t1 set … where name in(select name from user where…);效率极其低下。
- 【强制】禁用procedure、function、trigger、views、event、外键约束。因为他们消耗数据库资源,降低数据库实例可扩展性。推荐都在程序端实现。
- 【建议】禁用insert into …on duplicate key update…、replace into等语句,在高并发环境下,极容易导致死锁。
- 【强制】禁止联表更新语句,如update t1,t2 where t1.id=t2.id…。
目录
- 1. 规范背景与目的
- 2. 设计规范
- 2.1. 数据库设计
- 2.1.1. 库名
- 2.1.2. 表结构
- 2.1.3. 列数据类型优化
- 2.1.4. 索引设计
- 2.1.5. 分库分表、分区表
- 2.1.6. 字符集
- 2.1.7. 一个规范的建表语句示例
- 2.2. SQL编写
- 2.2.1. DML语句
- 2.2.2. 多表连接
- 2.2.3. 事务
- 2.2.4. 排序和分组
- 2.2.5. 线上禁止使用的SQL语句
- 2.1. 数据库设计
- 1. 规范背景与目的
- 2. 设计规范
- 2.1. 数据库设计
- 2.1.1. 库名
- 2.1.2. 表结构
- 2.1.3. 列数据类型优化
- 2.1.4. 索引设计
- 2.1.5. 分库分表、分区表
- 2.1.6. 字符集
- 2.1.7. 一个规范的建表语句示例
- 2.2. SQL编写
- 2.2.1. DML语句
- 2.2.2. 多表连接
- 2.2.3. 事务
- 2.2.4. 排序和分组
- 2.2.5. 线上禁止使用的SQL语句
- 2.1. 数据库设计
时间:2019-09-23 13:54:37 阅读(7)