This article brings you relevant knowledge aboutmysql, which mainly introduces issues related to database design specifications. When using MySQL database, you need to follow certain specifications, use strengths and avoid weaknesses, I hope to be able to Help or guide RD, QA, OP and other technical personnel to make database designs suitable for online business.
Recommended learning:mysql video tutorial
MySQL database and Oracle, SQL Server Compared with other databases, it has its own core advantages and disadvantages. When we use the MySQL database, we need to follow certain standards and maximize our strengths and avoid weaknesses. This specification is intended to help or guide RD, QA, OP and other technical personnel to make a database design suitable for online business. Standardize database changes and processing procedures, database table design, SQL writing, etc. to ensure the stable and healthy operation of the company's business system.
All the following specifications will be marked according to three levels: [High Risk], [Mandatory], and [Recommended], and the compliance priority is from high to low.
For designs that do not meet the two levels of [High Risk] and [Mandatory], the DBA will force the design back and require modification.
[Mandatory] Use lowercase to help improve typing speed and avoid errors caused by case sensitivity.
[Mandatory] No spaces, use underscores instead.
[Mandatory] There are no numbers in the name, only English letters.
[Mandatory] A valid and understandable name.
[Mandatory] Name should be self-explanatory.
[Mandatory] The name should not exceed 32 characters.
[Mandatory] Avoid using prefixes.
[Mandatory] Follow all the above general naming rules.
[Mandatory] Use the singular number.
[Mandatory] The name format of the library: business system name_subsystem name.
[Mandatory] Generally, the naming format of the sub-library name is library wildcard name_number, and the number increases from 0, such as northwind_001. The name format of the sub-library based on 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. Create database SQL example:
create database db_name default character set utf8;
[Mandatory] Comply with all the above general naming rules.
[Mandatory] Use the singular number.
[Mandatory] Try to reflect the join relationship between the table names of related modules, such as user table and user_login table.
[Mandatory] The character set must be explicitly specified as utf8 or utf8mb4 when creating a table.
[Mandatory] The table storage engine type must be explicitly specified when creating a table. If there are no special requirements, it will always be InnoDB. When it is necessary to use a storage engine other than InnoDB/MyISAM/Memory, it must pass DBA review before being used in a production environment. Because InnoDB tables support important features of relational databases such as transactions, row locks, downtime 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 recommended first.
[Mandatory] Comment must be included when creating a table.
[Mandatory] About the primary key: (1) Name it id, type int or bigint, and auto_increment; (2) Do not set the field that identifies the subject of each row in the table as the primary key. , it is recommended to set it to other fields such as user_id, order_id, etc., and create 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 splits and a large number of random I/O, resulting in performance degradation.
[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 row data to facilitate troubleshooting.
[Recommendation] All fields in the table must have NOT NULL attributes, and the business can define DEFAULT values as needed. Because using NULL values will cause problems such as each row occupying additional storage space, data migration is prone to errors, and aggregate function calculation results are biased.
[Recommendation] It is recommended to split large fields such as blob and text in the table vertically into other tables, and select only when you need to read these objects.
[Suggestion] Anti-paradigm design: redundantly add fields that often require join queries in other tables. For example, the username attribute is redundant in user_account, user_login_log and other tables, reducing 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 capture a snapshot of the source table, and the name must start with bak_. Intermediate tables and backup tables are cleaned regularly.
【强制】对于超过 100W 行的大表进行 alter table,必须经过 DBA 审核,并在业务低峰期执行。因为 alter table 会产生表锁,期间阻塞对于该表的所有写入,对于业务可能会产生极大影响。
【强制】遵守以上全部一般命名规则。
【建议】尽可能选择短的或一两个单词。
【强制】避免使用保留字作为字段名称:order,date,name 是数据库的保留字,避免使用它。可以为这些名称添加前缀使其易于理解,如 user_name,signup_date 等。
【强制】避免使用与表名相同的字段名,这会在编写查询时造成混淆。
【强制】在数据库模式上定义外键。
【强制】避免使用缩写或基于首字母缩写词的名称。
【强制】外键列必须具有表名及其主键,例如:blog_id 表示来自表博客的外键 id。
【建议】表中的自增列(auto_increment 属性),推荐使用 bigint 类型。因为无符号 int 存储范围为 0~4,294,967,295(不到 43 亿),溢出后会导致报错。
【建议】业务中选择性很少的状态 status、类型 type 等字段推荐使用 tinytint 或者 smallint 类型节省存储空间。
【建议】业务中 IP 地址字段推荐使用 int 类型,不推荐用 char(15)。因为 int 只占 4 字节,可以用如下函数相互转换,而 char(15) 占用至少 15 字节。
select inet_aton('192.168.2.12'); select inet_ntoa(3232236044);
Java 保存字符串ip 转 int 类型
public static long ipToLong(String addr) { String[] addrArray = addr.split("\\."); long num = 0; for (int i = 0; i < addrArray.length; i++) { int power = 3 - i; num += ((Integer.parseInt(addrArray[i]) % 256 * Math.pow(256, power))); } return num; } public static String longToIp(long i){ return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + (i & 0xFF); }
【建议】不推荐使用 enum,set。 因为它们浪费空间,且枚举值写死了,变更不方便。推荐使用 tinyint 或 smallint。
【建议】不推荐使用 blob,text 等类型。它们都比较浪费硬盘和内存空间。在加载表数据时,会读取大字段到内存里从而浪费内存空间,影响系统性能。建议和 PM、RD 沟通,是否真的需要这么大字段。InnoDB 中当一行记录超过 8098 字节时,会将该记录中选取最长的一个字段将其 768 字节放在原始 page 里,该字段余下内容放在 overflow-page 里。不幸的是在 compact 行格式下,原始 page 和 overflow-page 都会加载。
【建议】存储金钱的字段,建议用 int 以分为单位存储,最大数值约 4290 万,程序端乘以 100 和除以 100 进行存取。因为 int 占用 4 字节,而 double 占用 8 字节,空间浪费。
【建议】文本数据尽量用 varchar 存储。因为 varchar 是变长存储,比 char 更省空间。MySQL server 层规定一行所有文本最多存 65535 字节,因此在 utf8 字符集下最多存 21844 个字符,超过会自动转换为 mediumtext 字段。而 text 在 utf8 字符集下最多存 21844 个字符,mediumtext 最多存 2^24/3 个字符,longtext 最多存 2^32 个字符。一般建议用 varchar 类型,字符数不要超过 2700。
【建议】时间类型尽量选取 timestamp。因为 datetime 占用 8 字节,timestamp 仅占用 4 字节,但是范围为 1970-01-01 00:00:01 到 2038-01-01 00:00:00。更为高阶的方法,选用 int 来存储时间,使用 SQL 函数 unix_timestamp() 和 from_unixtime() 来进行转换。
【强制】InnoDB 表必须主键为 id int/bigint auto_increment,且主键值禁止被更新。
【建议】主键的名称以 pk_ 开头,唯一键以 uk_ 开头,普通索引以 ix_ 开头,一律使用小写格式,以表名/字段的名称或缩写作为后缀。
【强制】InnoDB 和 MyISAM 存储引擎表,索引类型必须为 BTREE;MEMORY 表可以根据需要选择 HASH 或者 BTREE 类型索引。
【强制】单个索引中每个索引记录的长度不能超过 64KB。
【建议】单个表上的索引个数不能超过 7 个。
【建议】在建立索引时,多考虑建立联合索引,并把区分度最高的字段放在最前面。如列 user_id 的区分度可由 select count(distinct user_id) 计算出来。
【建议】在多表 join 的 SQL 里,保证被驱动表的连接列上有索引,这样 join 执行效率最高。
【建议】建表或加索引时,保证表里互相不存在冗余索引。对于 MySQL 来说,如果表里已经存在 key(a, b),则 key(a) 为冗余索引,需要删除。
【建议】如果选择性超过 20%,那么全表扫描比使用索引性能更优,即没有设置索引的必要。
【强制】分区表的分区字段(partition-key)必须有索引,或者是组合索引的首列。
【强制】单个分区表中的分区(包括子分区)个数不能超过 1024。
【强制】上线前 RD 或者 DBA 必须指定分区表的创建、清理策略。
【强制】访问分区表的 SQL 必须包含分区键。
【建议】单个分区文件不超过 2G,总大小不超过 50G。建议总分区数不超过 20 个。
【强制】对于分区表执行 alter table 操作,必须在业务低峰期执行。
【强制】采用分库策略的,库的数量不能超过 1024。
【强制】采用分表策略的,表的数量不能超过 4096。
【建议】单个分表不超过 500W 行,ibd 文件大小不超过 2G,这样才能让数据分布式变得性能更佳。
【建议】水平分表尽量用取模方式,日志、报表类数据建议采用日期进行分表。
【强制】数据库本身库、表、列所有字符集必须保持一致,为 utf8 或 utf8mb4。
【强制】前端程序字符集或者环境变量中的字符集,与数据库、表的字符集必须一致,统一为 utf8。
【建议】新的代码不要用 model,推荐使用手动拼 SQL + 绑定变量传入参数的方式。因为 model 虽然可以使用面向对象的方式操作 db,但是其使用不当很容易造成生成的 SQL 非常复杂,且 model 层自己做的强制类型转换性能较差,最终导致数据库性能下降。
【建议】前端程序连接 MySQL 或者 Redis,必须要有连接超时和失败重连机制,且失败重试必须有间隔时间。
【建议】前端程序报错里尽量能够提示 MySQL 或 Redis 原生态的报错信息,便于排查错误。
【建议】对于有连接池的前端程序,必须根据业务需要配置初始、最小、最大连接数,超时时间以及连接回收机制,否则会耗尽数据库连接资源,造成线上事故。
【建议】对于 log 或 history 类型的表,随时间增长容易越来越大,因此上线前 RD 或者 DBA 必须建立表数据清理或归档方案。
【建议】在应用程序设计阶段,RD 必须考虑并规避数据库中主从延迟对于业务的影响。尽量避免从库短时延迟(20 秒以内)对业务造成影响,建议强制一致性的读开启事务走主库,或更新后过一段时间再去读从库。
【建议】多个并发业务逻辑访问同一块数据(InnoDB 表)时,会在数据库端产生行锁甚至表锁导致并发下降,因此建议更新类 SQL 尽量基于主键去更新。
【建议】业务逻辑之间加锁顺序尽量保持一致,否则会导致死锁。
【建议】对于单表读写比大于 10:1 的数据行或单个列,可以将热点数据放在缓存里(如 Memcached 或 Redis),加快访问速度,降低 MySQL 压力。
一个较为规范的建表语句为:
create table user ( `id` bigint(11) not null auto_increment, `user_id` bigint(11) not null comment '用户 ID', `username` varchar(45) not null comment '登录名', `email` varchar(30) not null comment '邮箱', `nickname` varchar(45) not null comment '昵称', `avatar` int(11) not null comment '头像', `birthday` date not null comment '生日', `gender` tinyint(4) default '0' comment '性别', `intro` varchar(150) default null comment '简介', `resume_url` varchar(300) not null comment '简历存放地址', `register_ip` int not null comment '用户注册时的源 IP', `review_status` tinyint not null comment '审核状态,1-通过,2-审核中,3-未通过,4-尚未提交审核', `create_time` timestamp not null comment '记录创建的时间', `update_time` timestamp not null comment '资料修改的时间', primary key (`id`), unique key `idx_user_id` (`user_id`), key `idx_username`(`username`), key `idx_create_time`(`create_time`, `review_status`) ) engine = InnoDB default charset = utf8 comment = '用户基本信息';
【强制】select 语句必须指定具体字段名称,禁止写成 *。因为 select * 会将不该读的数据也从 MySQL 里读出来,造成网卡压力。
【强制】insert 语句指定具体字段名称,不要写成 insert into t1 values(…),道理同上。
【建议】insert into … values(xx),(xx),(xx)…,这里 xx 的值不要超过 5000 个。值过多虽然上线很快,但会引起主从同步延迟。
【建议】select 语句不要使用 union,推荐使用 union all,并且 union 子句个数限制在 5 个以内。因为 union all 不需要去重,节省数据库资源,提高性能。
【建议】in 值列表限制在 500 以内。例如 select … where user_id in(…500 个以内…),这么做是为了减少底层扫描,减轻数据库压力从而加速查询。
【建议】事务里批量更新数据需要控制数量,进行必要的 sleep,做到少量多次。
【强制】事务涉及的表必须全部是 InnoDB 表。否则一旦失败不会全部回滚,且易造成主从库同步终端。
【强制】写入和事务发往主库,只读 SQL 发往从库。
【强制】除静态表或小表(100 行以内),dml 语句必须有 where 条件,且使用索引查找。
[Mandatory] It is forbidden to use hints 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, so we have to trust the MySQL optimizer.
[Mandatory] The field types around the equal sign in the where condition must be consistent, otherwise the index cannot be used.
[Recommendation] select|update|delete|replace must have a where clause, and the conditions of the where clause must use index search.
[Mandatory] It is strongly not recommended to perform a full table scan on a large table in a production database, but a full table scan can be performed on a static table with less than 100 rows. The amount of query data should not exceed 25% of the number of table rows, otherwise the index will not be utilized.
[Mandatory] It is forbidden to use only fully fuzzy like conditions for search in the where clause. There must be other equal value or range query conditions, otherwise the index cannot be used.
[Recommendation] Do not use functions or expressions in index columns, 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 into unions, and then create 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).
[Suggestion] Paging query, when the starting point of limit is high, you can use filter conditions to filter first. For example, select a, b, c from t1 limit 10000, 20; is optimized to: select a, b, c from t1 where id > 10000 limit 20;.
[Mandatory] Cross-DB join statements are prohibited. Because this can reduce coupling between modules and lay a solid foundation for database splitting.
[Mandatory] It is prohibited to use join in business update SQL statements, such as update t1 join t2….
[Recommendation] It is not recommended to use subqueries. It is recommended to split the subquery SQL and combine the program with multiple queries, or use join instead of subqueries.
[Recommendation] In online environment, multi-table join should not exceed 3 tables.
[Recommendation] It is recommended to use aliases for multi-table connection 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 multi-table join, try to select the table with smaller result set as the driving table to join other tables.
[Recommendation] The number of rows in the insert|update|delete|replace statement operation in the transaction should be controlled within 2000, and the where sub The number of parameters passed in the in list in the sentence is controlled within 500.
[Recommendation] When operating data in batches, you need to control the transaction processing interval and perform necessary sleep. The generally recommended value is 5-10 seconds.
[Recommendation] For insert operations in 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. It is recommended online that the transaction isolation level is repeatable-read.
[Recommendation] The transaction should contain no more than 5 SQL statements (excluding payment business). Because too long transactions will lead to avalanche problems such as locking data for a long time, MySQL internal cache, excessive connection consumption, etc.
[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 gap locks will be generated and the lock range will be expanded internally, resulting in reduced system performance. , resulting in a deadlock.
[Recommendation] Try to move some typical external calls out of the transaction, such as calling Web Service, accessing file storage, etc., so as to avoid the transaction being too long.
[Recommendation] For select statements that are strictly sensitive to MySQL master-slave delay, please enable transactions to force access to the main database.
[Recommendation] Reduce the use of order by, and communicate with the business if you can not sort without sorting, or put the sorting in Do it on the terminal. Statements such as order by, group by, and distinct consume more CPU, and the CPU resources of the database are extremely precious.
[Recommendation] SQL such as order by, group by, distinct, try to use the index to directly retrieve the sorted data. For example, where a = 1 order by can use key(a, b).
[Recommendation] For queries that include order by, group by, and distinct, the result set filtered by the where condition should be kept within 1,000 rows, otherwise SQL will be very slow.
[High risk] Disable update|delete t1 ... where a = XX limit XX; update statement for limit. Because it will lead to master-slave inconsistency, leading to data confusion. It is recommended to add order by PK.
[High risk] It is forbidden to use correlated subqueries, such as update t1 set … where name in (select name from user where …);, which is extremely inefficient.
[Mandatory] Disable procedure, function, trigger, views, event, and foreign key constraints. Because they consume database resources and reduce database instance scalability. Recommendations are all implemented on the program side.
[Mandatory] Disable insert into … on duplicate key update … In a high-concurrency environment, it will cause master-slave inconsistency.
[Mandatory] Joint table update statements are prohibited, such as update t1, t2 where t1.id = t2.id….
Recommended learning:mysql video tutorial
The above is the detailed content of Summarize and organize MySQL database design specifications. For more information, please follow other related articles on the PHP Chinese website!