数据库设计规范
[if !supportLists]1. [endif]表名列名小写、以下划线分隔
[if !supportLists]2. [endif]数据库对象禁用MySQL的保留关键字
[if !supportLists]3. [endif]对象命名见名识义即可,小于3 2个字符
[if !supportLists]4. [endif]临时库表以tmp为前缀、日期为后缀,备份库表必须以bak为前缀、日期为后缀
[if !supportLists]5. [endif]所有存储相同数据的列名和列类必须一致
[if !supportLists]6. [endif]所有的表必须使用innoDB存储引擎
[if !supportLists]7. [endif]所有库表字符集统一使用UTF-8,避免字符集转换带来乱码,ASCII码一字节,汉字3字节
[if !supportLists]8. [endif]所有表与字段需使用comment从句添加注释
[if !supportLists]9. [endif]尽量控制单表数据量大小在500万以内,使用历史归档、分库分表等手段来控制
[if !supportLists]10. [endif]谨慎使用分区表,建议使用物理分表的方式管理大数据
[if !supportLists]11. [endif]尽量冷热数据分离,减少表的宽度以减少磁盘的IO,保证热数据的缓存命中率,利用更有效的缓存,避免读入无用的冷数据,把经常使用的列放入一个表中
[if !supportLists]12. [endif]禁止在表中建立预留字段,预留字段类型修改时会对表进行锁定,严重影响其并发性
[if !supportLists]13. [endif]禁止在数据库中存储图片、文件等二进制数据
[if !supportLists]14. [endif]禁止在线上服务器做压力测试
[if !supportLists]15. [endif]禁止从开发、测试环境直连生产环境数据库
索引设计规范
[if !supportLists]1. [endif]限制单张表的索引,建议不超过5个,禁止给标准的每一列添加索引
[if !supportLists]2. [endif]每张InnoDB表至少要有一个主键,不要选用频繁变动的列作为主键,建议使用自增ID作为主键
[if !supportLists]3. [endif]区分度最高的、字段长度最小的、使用最频繁的列放在联合索引的最左侧
[if !supportLists]4. [endif]对于频繁的查询优先考虑使用覆盖索引
[if !supportLists]5. [endif]不建议使用外键约束,但一定要在表与表之间的关联键上建立索引
数据库字段设计规范
1. 优先选择存储需要最小的数据类型,将字符串转化为整型 ,比如INET_ATON(‘255.255.255.255’),使用INET_NTOA转回
2.非负整数使用无符号的整型进行存储,增加一倍的存储数值
(1)Varchar(N)中N代表的是字符数而不是字节数
(2)使用UTF8存储汉字varchar(255)需要765字节
(3)过长的长度会消耗内存
3.避免使用TEXT、BLOB 和ENUM类型,禁止使用数值作为ENUM的枚举值
4.尽可能把所有列设置为NOT NULL,防止空指针异常
5.使用DATETIME与TIMESTAMP类型存储时间
6.财务相关的金额类型必须使用Decimal类型以保证精度
数据库SQL开发规范
[if !supportLists]1. [endif]建议使用预编译语句进行数据库操作,提高效率,防止注入
[if !supportLists]2. [endif]尽量避免数据类型的隐式转换
[if !supportLists]3. [endif]充分利用表上已经存在的索引,尽量避免模糊查询
[if !supportLists]4. [endif]禁止使用SELECT *,必须使用SELECT<字段列表>查询,解决网络带宽与CPU、IO资源,减少表结构变更带来的影响
[if !supportLists]5. [endif]禁止使用不含字段列表的INSERT语句
[if !supportLists]6. [endif]尽量避免使用子查询,可以转化为join操作,节约CPU与IO资源
[if !supportLists]7. [endif]避免使用JOIN关联过多的表,建议不超过5个
[if !supportLists]8. [endif]减少同数据库的交互操作,数据库更适合批量操作
[if !supportLists]9. [endif]使用IN替换OR
[if !supportLists]10. [endif]禁止使用order by rand()进行随机排序,节约大量CPU与IO
[if !supportLists]11. [endif]禁止在WHERE从句中对列进行函数转换与计算,会导致其无法使用索引
[if !supportLists]12. [endif]在明显不会有重复值时使用UNION ALL而不是UNION
[if !supportLists]13. [endif]拆分复杂的大SQL为多个小SQL
数据库操作行为开发规范
[if !supportLists]1. [endif]超过100万行的批量写操作,要分批多次进行操作,以免造成阻塞
[if !supportLists]2. [endif]对于大表使用pt-online-schema-change修改表结构,避免主从延迟与表锁
[if !supportLists]3. [endif]禁止为程序所用的账户赋予super权限,遵循权限最小原则,程序所用的账户禁止拥有drop权限
[if !supportLists]4. [endif]禁止跨库查询,不同数据库不同账号,以降低耦合度与安全风险
网友评论