Mysql development specification

1. Table design

1. Using the ER model, first follow the paradigm design, and then denormalize the design according to actual needs.

2. The library name, table name and field name must use lowercase letters, separated by "_" (except TICKET library).

3. The library name, table name and field name should not be too long. It is recommended to use nouns instead of verbs, and avoid using system keywords.

4. Tables and fields should have comments to explain their meanings. For redundant fields, special instructions should be given to their maintenance methods, and foreign key fields should be explained to which table to refer to.

5. It is recommended to use the InnoDB storage engine.

6. Try to keep table row lengths small. The length of all fields in a table should not exceed half of a data block (16K).

7. The primary key should choose the AUTO_INCREMENT column as much as possible, and the column with actual semantics can be used in special cases. [FAQ]

8. Keep the field names and data types consistent, for example, do not use varchar() for member_id.

9. Large tables must have a clear data retention policy.

10. To store exact floating-point numbers, DECIMAL must be used instead of FLOAT and DOUBLE.

11. It is recommended to use UNSIGNED to store non-negative values.

12. It is recommended to use INT UNSIGNED to store IPV4. [FAQ]

13. The length is not added to the definition of shaping, such as using INT instead of INT(4). [FAQ]

14. Use short data types, such as TINYINT UNSIGNED when the value range is 0-80.

15. It is not recommended to use the ENUM type, use TINYINT instead.

16. Try not to use TEXT and BLOB types.

17. It is recommended to use CHAR() when the number of characters is fixed and small, such as MD5, ID number, gender, etc.

18. VARCHAR(N), N represents the number of characters not the number of bytes, such as VARCHAR(255), which can store up to 255 Chinese characters, and N needs to be selected according to the actual width.

19. VARCHAR(N), N should be as small as possible, because the maximum length of all VARCHAR fields in a MySQL table is 65535 bytes. When performing memory operations such as sorting and creating temporary tables, the length of N will be used to apply for memory.

20. Select UTF8 for the table character set.

21. Use VARBINARY to store case-sensitive variable-length strings or binary content.

22. Use the YEAR type to store the year, and the DATE type to store the date.

23. It is recommended to use the TIMESTAMP type to store the time (accurate to the second), because TIMESTAMP uses 4 bytes and DATETIME uses 8 bytes. Pay attention to the update problem when using TIMESTAMP. 【FAQ】

24. The field should be defined as NOT NULL as much as possible.

25. Split the fields that are too large and those with low access frequency into separate tables for storage, and separate hot and cold data.

26. It is forbidden to use VARBINARY and BLOB to store pictures, files, etc. in the database.

27. Temporary library and table names must be prefixed with tmp and suffixed with date.

28. The use of partition tables is prohibited.

2. Scattered tables

1. For simple field types and few fields, it is recommended to control the data volume of a single table below 5000w.

2. The hash, range, and lookup table can be used in combination to disperse the table.

3. If the table is divided by date and time, it must conform to the YYYY[MM][DD][HH] format, such as 2013071601. The year must be represented by 4 digits. For example, user_20110209 is distributed daily, and user_201102 is distributed monthly.

3. Index Specifications

1. Non-unique indexes must be named according to "idx_field name_field name[_field name]". If the field name is too long, abbreviations can be used.

2. The unique index must be named according to "uniq_field name_field name[_field name]", and the field name can be abbreviated if it is too long.

3. Index names must use lowercase.

4. The number of fields in the index is recommended not to exceed 3.

5. The number of indexes in a single table is controlled within 5.

6. A unique key consists of less than 3 fields. When the field is an integer, according to the table design specification, consider using the unique key as the primary key.

7. The unique key does not duplicate the primary key.

8. The order of index fields needs to consider the cardinality of the field value, and the cardinality with a larger cardinality is placed first.

9. Redundant and duplicate indexes are prohibited.

10. Foreign keys are not recommended.

11. When querying a joint table, the data type of the JOIN column must be the same, and an index must be established.

12. Do not index on low cardinality columns such as gender, status, type.

13. The fields of ORDER BY, GROUP BY, and DISTINCT need to be added after the index.

14. Use EXPLAIN to judge whether the SQL statement uses indexes reasonably, and try to avoid extra columns: Using File Sort, Using Temporary.

15. UPDATE and DELETE statements need to add indexes according to WHERE conditions. Columns that are updated frequently are not suitable for creating indexes.

16. When indexing a VARCHAR field with a long length, add a crc32 or MD5 Hash field to index the Hash field.

17. Ordinary length strings use prefix indexing as appropriate.

18. Create a joint index reasonably (avoid redundancy), (a,b,c) is equivalent to (a), (a,b), (a,b,c). Columns with high cardinality values ​​come first in range queries. If you can avoid returning to the table (the detection can be completed in the index), you can also add a joint index as appropriate.

19. Make reasonable use of covering indexes.

20. Do not perform data operations or function operations on indexed columns (which will result in inability to use indexes, or full table scans).

21. SQL changes need to confirm whether the index needs to be changed and notify the DBA.

22. Notify DBA to offline related indexes when SQL is offline.

Fourth, SQL specification

1. Using prepared statement can provide performance and avoid SQL injection.

2. The value contained in IN in the SQL statement should not be too many. Use between and instead of IN for consecutive numbers.

3. UPDATE, DELETE statements try not to use LIMIT.

4. The appropriate type must be used in the WHERE condition to avoid implicit type conversion by MySQL. Numerical types must not be quoted; string types must be quoted.

5. The SELECT statement only gets the required fields. SELECT and INSERT statements must explicitly specify the field name, do not use SELECT *, do not use INSERT INTO table().

6. Use SELECT column_name1, column_name2 FROM table WHERE [condition] instead of SELECT column_name1 FROM table WHERE [condition] and SELECT column_name2 FROM table WHERE [condition].

7. Avoid mathematical operations or function operations in SQL statements, and it is easy to couple business logic and DB.

8. The INSERT statement uses batch submission (INSERT INTO table VALUES(),(),()...), and the number of values ​​should not be too many.

9. Avoid using stored procedures, triggers, functions, timers, etc. It is easy to couple business logic with DB, and there are certain bugs in MySQL's stored procedures, triggers, and functions.

10. Avoid JOINs and subqueries.

11. Use reasonable SQL statements to reduce the number of interactions with the database.

12. Do not use ORDER BY RAND(), use other methods to replace.

13. It is recommended to use a reasonable paging method to improve the efficiency of paging.

14. Use COUNT(*) instead of COUNT(primary_key) and COUNT(1) when counting the number of records in the table.

15. NULL values ​​cannot be compared directly with comparison operators, and is null and is not null should be used.

16. It is not recommended to use % prefixed fuzzy queries, such as LIKE "%weibo", which will result in a full table scan.

17. Avoid unnecessary sorting and hand over sorting to the application layer as appropriate.

18. Avoid SQL hints (USE INDEX, FORCE INDEX, etc.) in the code.

19. Use parallelism with caution. High concurrent SQL statements need to be submitted to the DBA for stress testing.

20. To query a column of datetime type, you do not need to use the DATE_FORMAT or STR_TO_DATE() function.

21. Split complex SQL into multiple small SQLs to avoid large transactions.

22. Avoid using OR conditions.

23. Avoid functions with uncertain results such as now(), rand(), sysdate(), and current_user() in SQL.

24. Avoid updating multiple tables at the same time with a single SQL statement.

25. It is forbidden to perform QUERY of background management and statistical functions on the slave library, and the statistical slave library can be used.

26. Negative queries, such as not in, !=, not like, are prohibited.

V. Code of Conduct

1. Changes in table structure must be notified to DBA for review.

2. It is forbidden to do database stress testing online, and it is forbidden to directly connect to the database from the test environment.

3. The existence of application accounts with super permissions is prohibited.

4. Application accounts with DDL and DCL permissions are prohibited.

5. The database scheme selection and design of important projects must be notified to the DBA in advance.

6. Import and export data in batches, and update data in batches such as UPDATE and DELETE operations, which must be reviewed by the DBA, and the service must be observed during the execution process.

7. When the product fails due to the database, if it is attacked, the DBA must be notified in time to facilitate the maintenance of service stability.

8. If there is a bug in the program of the business department that affects the database service, the DBA must be notified in time to maintain the stability of the service.

9. When the business department promotes activities or launches new functions, the DBA must be notified in advance to conduct service and traffic evaluation, and allow necessary time for the DBA to complete the expansion.

10. If the data is lost due to human misoperation in the business department, and the data needs to be restored, the DBA must be contacted as soon as possible, and important clues such as accurate time and place, misoperation statements, etc. must be provided.

11. When submitting online table creation and modification requirements, all SQL statements involved (including INSERT, DELETE, and UPDATE) must be specified in detail, so as to facilitate the review and optimization of the DBA.

12. Do not store business logic in a MySQL database.

6. FAQ

1. Table Design

6. Try to choose the AUTO_INCREMENT type. Columns with actual semantics are only suitable for scenarios where there are more reads and fewer writes and the amount of reads and writes is disparate, such as using member_id as the primary key.

12. Convert through the MySQL functions inet_ntoa and inet_aton.

13. The numbers after the parentheses of the numeric type just represent the width and have nothing to do with the storage range.

23. For multi-column TIMESTAMP, attention should be paid to the update problem. In particular, specifying automatic defaults or updates for TIMESTAMP columns other than column 1 must be disabled by explicitly assigning the 1st TIMESTAMP column a constant DEFAULT value.

http://dev.mysql.com/doc/refman/5.1/zh/column-types.html#timestamp-4-1
7. References

1. MySQL system keywords

http://dev.mysql.com/doc /refman/5.5/en/reserved-words.html
2.mysql development specification

http://www.iamcjd.com/?p=1237#MySQL-1-3


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326255178&siteId=291194637