37 tips MySQL database

Quoted from: Java technology stack

1, how to quickly master the MySQL?

Cultivate an interest

Interest is the best teacher, no matter what to learn knowledge, interest can greatly improve learning efficiency. Of course, learning MySQL 5.6 is no exception.

Solid foundation

Great emphasis on the field of computer technology foundation, just learning may not realize this, along with in-depth technical applications, only has a solid foundation of knowledge, in order to go faster and farther on the road technology. For MySQL for learning, SQL statement is one of the most basic part, many of the operations are achieved through the SQL statement. So in the process of learning, readers should be more to write SQL statements, for the same function, using different implementations statement to complete, thus a deep understanding of their differences.

In time to learn new knowledge

Correct and effective use of search engines, you can search a lot of knowledge about MySQL 5.6. Meanwhile, referring to other people's ideas to solve the problem, we can also learn from the experience of others, timely access to the latest technical information.

More practice operation

Database system is highly operational, require more hands-on. The problem can be found in the actual operation, and ways of thinking and problem-solving ideas, the only way to improve the operational capacity of actual combat.

2, how to choose the type of server?

MySQL server configuration window of each parameter in the following meaning.
Server Configuration Type [] This option is used to set the type of server. Click the Options button to the right down, you can see include three options.

Specific meaning three options are as follows:
  • Development Machine (development machine): This option represents the typical personal desktop workstations. Running multiple applications on a desktop machine is assumed. The MySQL server is configured to use a minimum of system resources.

  • Server Machine (server): This option represents the server, MySQL server can be run in conjunction with other applications, such as FTP, email and web servers. MySQL server is configured to use an appropriate proportion of system resources.

  • DedicatedMySQL Server Machine (dedicated MySQL server): This option represents the only server running MySQL services. Assuming that runs without running other applications. MySQL server is configured to use all available system resources. As a beginner, it is recommended to select [DevelopmentMachine] (developer machine) options, so take up less system resources.

3, how to choose the storage engine

Different storage engines have their own characteristics, to suit different needs, as shown in the following table. In order to make a choice:

  • We first need to consider each different storage engine which provides the functionality. If you want to provide commit, rollback, and crash recovery capabilities of transaction-safe (ACID compliant) capabilities, and requirements to achieve concurrency control, InnoDB is a good choice. If the data table is mainly used to insert and query records, the MyISAM engine offers high efficiency; if only temporarily stored data, the amount of data, and does not require high data security, you can choose the data stored in the memory the Memory engine, MySQL use the engine as a temporary table to store intermediate results of the query. If only INSERT and SELECT operations, you can choose Archive engine, Archive storage engine to support high concurrent insert operation, but the transaction itself is not safe. Archive storage engine is adapted to store archival data, logging information may be used as Archive Engine.

  • Which engine using selected according to need to be flexible, a plurality of database tables may be used in different engines to meet various performance requirements and practical.

  • Use appropriate storage engine, it will improve the performance of the entire database.

4, how to view the default storage engine?

Use SHOW ENGINES statement to view the system in all storage engines, including the default storage engine. Can see the current database system has five storage engine, the default is MyISAM. You can also use a direct way to see the default storage engine. The results show a direct current default storage engine is MyISAM.

5, delete the table to be cautious

Table delete operation definition table will be deleted and the data tables together, and MySQL during a delete operation, without any confirmation prompt message, and therefore while the delete operation should be carefully. Before deleting the table, it is best to back up the data in the table, so that when operational errors, data can be restored in order to avoid irreversible consequences.

Similarly, when using ALTER TABLE to modify the basic operating table, before you perform the procedures should also ensure a complete backup of the data, because changes to the database can not be revoked, if an unwanted field is added, you can delete it; the same, if you delete a column required, all data following the column will be lost.

6, each table must have a primary key it?

Not every table must have a primary key, in general, if the connecting operation between a plurality of tables, the need to use the primary key. And therefore it does not need to create a primary key for each table, and in some cases preferred not to use a primary key.

7, each table can choose the storage engine?

Foreign key constraints (FOREIGN KEY) can not be cross-engine use. MySQL supports multiple storage engine, each table can specify a different storage engines, but be warned: the foreign key constraint is used to ensure referential integrity of the data, if necessary correlation between foreign key table, but specify a different storage engine, between these tables can not create a foreign key constraint. So, choose the storage engine is not completely arbitrary.

8, with AUTO_INCREMENT field value is constrained from the beginning of it?

By default, in MySQL, AUTO_INCREMENT initial value is 1, each of the new record, the field value incremented by one. Set the self-energizing properties (the AUTO_INCREMENT) when inserted record can also specify the value of the self-energizing field of a first article, such self-energizing field value newly inserted record increments from the initial value, as in the first record is inserted in tb_emp8 , specify the id value 5, the value id after the inserted recording will increase from 6 starts up. When adding a unique primary key constraint, often you need to set the attribute field is automatically increased.

9, with the difference between the two TIMESTAMP DATATIME

TIMESTAMP and DATETIME addition to the different byte storage and support range, there is a maximum difference is: DATETIME, date data storage, according to the actual storage format of the input, i.e., what is stored on what input, regardless of the time zone; TIMESTAMP value and storage is UTC (Coordinated Universal time) to save the format to the current time zone conversion storage, and converted back to the current time zone upon retrieval. That is, when a query, depending on the current time zone, the time value displayed is different.

10, select what type of data the methods and skills are?

MySQL provides a number of data types, in order to optimize storage, improve database performance, should use the most precise type in all cases. I.e. all the column may indicate the type of value, stores the minimum type of use.

Integer and floating-point numbers

If no fractional part, is used to store the integer data; if necessary represent the fractional part, the use of floating point type. For floating point data column, the value will be stored in the column definition decimal rounding. For example, if the range of values ​​of the column is 1~99999, when using an integer, is the best type MEDIUMINT UNSIGNED; decimals if necessary to store, use the FLOAT type. FLOAT and DOUBLE types, including floating-point type. DOUBLE FLOAT type than the type of high precision, therefore, when stored as high precision required, should be selected DOUBLE type.

Floating-point and fixed-point

Float FLOAT, DOUBLE DECIMAL fixed point with respect to the advantages: the length in certain circumstances, floating point data can represent a larger range. However, because floating-point error prone, thus when a relatively high accuracy requirements, it is recommended to store DECIMAL. DECIMAL string is stored in MySQL, used to define the currency for higher accuracy data requirements. In the data migration, float (M, D) is the definition of a non-standard SQL, database migration may be a problem, so it is best not to use. When the two floating-point subtraction and a comparison operation are also vulnerable, so when performing the calculation, must be careful. If the comparison value, DECIMAL type is preferably used.

Date and Time Types

MySQL has many data types for different kinds of dates and times, such as YEAR and TIME. If you only need to record year, YEAR type it can use; if only recording time, simply use the TIME type. If both need to record the date and time, or can be used TIMESTAMP DATETIME type. Since the range is less than the range TIMESTAMP DATETIME column, thus storing a large range DATETIME The date is preferably used. TIMESTAMP DATETIME also does not have a property. By default, when inserting a record but did not specify the value of TIMESTAMP this column, MySQL will TIMESTAMP column to the current time. Therefore, when the need to insert inserted simultaneously recording the current time, it is convenient to use TIMESTAMP, TIMESTAMP further more effective in space than DATETIME.

Features and choose between CHAR and VARCHAR

CHAR and VARCHAR difference:
  • Is the fixed length character CHAR, VARCHAR is a variable length character; CHAR trailing spaces will automatically delete the inserted data, VARCHAR trailing spaces are not deleted.

  • CHAR is a fixed length, so that its processing speed is faster than VARCHAR, but its drawback is a waste of storage space. Therefore, little storage, but the speed requirements may be used in the type of CHAR, VARCHAR type may be used and vice versa is achieved.

Storage Engine selection for CHAR and VARCHAR effects:
  • For MyISAM storage engine: a fixed length data is preferably used instead of a column of variable length data sequence. This allows the entire table static, so that faster data retrieval, a space for time.

  • For InnoDB storage engine: using variable-length data string, because InnoDB table storage format regardless of the fixed length and variable length, the use is not necessarily better than VARCHAR CHAR, VARCHAR but the actual length is stored, more to save space, so the disk I / O and the amount of data stored better.

ENUM and SET

ENUM can only take a single value, which is an enumerated list of data collection. Its legal value list allows up to 65 535 members. Thus, the need to select from a plurality of values ​​can be used when ENUM. For example: for gender field defined as ENUM type, you can only take one value from a 'male' or 'female' in. Preferably the multi-value SET. It's a legitimate list of supported maximum of 64 members.

An empty string is a valid SET value. When you need to take multiple values ​​for the use of SET type, such as: To store a person of interest, best to use SET type. ENUM and SET value is based on the form of a string, but internally, MySQL store them as a numerical value.

BLOB and TEXT

A BLOB is a binary string, TEXT non-binary string, both of which can store large volumes of information. BLOB main store pictures, audio and other information, and TEXT can only store plain text files. The use should distinguish between the two. Click here summarize the 55 MYSQL to face questions BAT interview.

11, MySQL how to use special characters?

Such as a single quote ( '), double quote ( "), backslash () like symbols, which can not be entered directly in MySQL, or will cause unexpected results. In MySQL, these special characters or transpose escape character, it is necessary to begin input backslash ( "\"), the input respectively single and double quotes should be (\ ') or (\ "), should be entered when entering a backslash (\ ), as well as other special characters carriage return (\ R & lt), linefeed (\ n-), tab (\ Tab), backspace (\ B) and the like. When inserting these special characters to the database, it must be escaped.

12, MySQL can store files?

In MySQL BLOB and TEXT field types can store large amount of data files, can use the data type text images, sounds, or a large capacity, such as web pages or documents. Although TEXT or BLOB may store large volumes of data, but the processing of these fields will reduce the performance of the database. If this is not necessary, you can select only the storage file path.

13, How MySQL perform a case-sensitive string comparisons?

In the Windows platform, MySQL is not case sensitive, so the string comparison function is not case-sensitive. If you want to perform a case-insensitive comparison, you can add keywords BINARY in front of the string. By default, for example, 'a' = 'A' returns a value of 1, if the keyword BINARY, BINARY'a '=' A 'result is 0, in the case of case-sensitive,' a 'and' A ' It is not the same.

14, how to get a date or time value portion of the year, month, day, etc. from the datetime value?

MySQL, date time value is stored as a string in the data table, it is possible to use different parts of the string functions are taken date and time values, such as a name field dt has a value of "2010-10-01 12:00 : 30 "If you just need to get in value, you can enter lEFT (dt, 4), so you get a left substring beginning of the string of length 4, that portion of the value YEAR; if you want to get the month value, you can enter MID (dt, 6,2), the sixth character string, length substring 2 dt is exactly the value of the month. Similarly, the position reader according to another date and time, and to obtain the corresponding calculated value.

15, how to change the default character set?

The CONVERT () function to change the default character set for the string, in the chapter start, to introduce the reader GUI graphical configuration tool mounted installation and configuration using MySQL, wherein a step is optional MySQL default character set. However, if you only change the character set, there is no need to re-run the configuration process again, here is an easy way to modify the configuration file. On Windows, MySQL configuration file named my.ini, the file in the MySQL installation directory below. default-character-set and character-set-server parameters to modify the configuration file, change it to the desired character set name, such as gbk, gb2312, latinl etc., restart the MySQL service after you modify, to take effect. Readers can be used to modify the character set SHOW VARIABLES LIKE 'character_set_ °%'; command to view the current character set, for comparison.

16, DISTINCT can be applied to all rows?

Query results, if necessary columns in descending order, you can use the DESC, the key can only be listed in descending order of their front. For example, to have multiple columns in descending order, it is necessary to add DESC keyword after the column name of each column. 

Different DISTINCT, DISTINCT portion can not be used. In other words, DISTINCT keyword is applied to all column and not only the first specified column behind it. For example, three query field s_id, f_name, f_price, if the combined value of these three fields are different in different records, the records will be all the check out.

17, ORDER BY and LIMIT can mix it?

When using the ORDER BY clause, should ensure that after positioned after FROM clause, if the LIMIT, ORDER BY must be located, if the order is incorrect clause, MySQL will produce an error message.

18, when to use quotation marks?

When the query, you will see the conditions of use in the WHERE clause, and some value added single quotes, while others did not add value. Single quotes used to define a string, if the value is compared with the string type column is necessary to define marks; and used for comparison with the values ​​do not need quotes.

19, you must use parentheses in the WHERE clause?

WHERE clause any time having AND and OR operators, parentheses should be clear sequence of operations. If the condition is more, even if we can determine the order of evaluation, the default order of evaluation may also cause SQL statements easy to understand, and therefore a clear order of operations with parentheses character, is a good habit.

20, the WHERE clause must be specified when you update or delete a table?

Can be seen in the previous section, all of the UPDATE and DELETE statements are all conditions specified in the WHERE clause. If the WHERE clause is omitted, the UPDATE or DELETE will be applied to all of the rows in the table.

Therefore, unless indeed intend to update or delete all records, or to pay attention to use UPDATE or DELETE statement without a WHERE clause. Advice before a table update and delete operations, use the SELECT statement to confirm the record to be deleted in order to avoid irreparable results. Click here summarize the 55 MYSQL to face questions BAT interview.

21, the index is so important for database performance, how to use it?

Select the correct index for the database is a complex task. If the index column less disk space is required and maintenance costs are less. If you create multiple composite index on a large table, the index file will be expanded soon.

On the other hand, the index can cover many more queries. You may need to experiment with several different designs, in order to find the most effective index. You can add, modify and delete indexes without affecting the database schema or application design. Therefore, you should try a number of different indexes to establish the optimal index.

22, try to use short index.

String type index field, if possible, should specify a prefix length. For example, if there is a CHAR (255) column, if the 10 or 30 characters in the front, the only multi-value, it is not necessary for the entire column index. Short index can not only speed up the search and save disk space and reduce I / O operations.

23, MySQL stored procedures and functions What is the difference?

In essence, they are all stored procedures. Function can only return a single value or a return statement by table objects; stored procedure return is not permitted, but can return out through the plurality of parameter values. Function more limited, can not use temporary tables, table variables can only be used, there are some functions are not available, and so on; and restrictions on the stored procedure is relatively less. Function can be used in the embedded SQL statements can be used as part of a call in the query SELECT statement; process is generally stored as a separate part is performed.

24, the stored procedure code can change?

Currently, MySQL does not provide modifications to the existing stored procedure code, and then if you have to modify the stored procedure, you must use the DROP statement to delete and re-write code, or create a new stored procedure.

25, the stored procedure can call other stored procedures do?

Stored procedure contains a user-defined set of SQL statements, you can use the CALL statement to call a stored procedure, of course, you can also use the CALL statement to call a stored procedure in another stored procedure, but you can not use the DROP statement to delete other stored procedures.

26, the stored procedure parameters not the same as the field names in the data table.

When defining a stored procedure parameter list, you should pay attention to the difference between the parameter name and the field name in the database table open, otherwise unpredictable results will occur.

27, the stored procedure parameter can be used Chinese?

Under normal circumstances, there may be cases stored procedure parameters of the incoming Chinese, such as a stored procedure to find the information to the user based on the user's name, the incoming parameter values ​​may be Chinese. Then you need to define a stored procedure when followed by the character set gbk, otherwise the Chinese call a stored procedure using parameters to be wrong, such as the definition userInfo stored procedure code is as follows:

CREATE PROCEDURE useInfo(IN u_name VARCHAR(50) character set gbk, OUT u_age INT) 

28. What is the difference in MySQL tables and views and links are?

Difference between the two:

  • (1) View SQL statement is compiled, the table is based on the visualization of the result set of SQL statements, rather than the table.

  • (2) there is no actual physical record view, and have the base table.

  • (3) Table of Contents, is a window view.

  • (4) the physical space occupied by the table view does not occupy physical space, but there is a logical view of the concept, the table can modify it in a timely manner, but only with a view to create the modified statements.

  • (5) See data table view is a way to query the data field consists of a table of some, but a collection of SQL statements. From a security point of view, the view can be prevented from contacting the user data table so that the user does not know the table structure.

  • (6) belongs to the global table mode table, the table is real; partial view mode table belongs, is the virtual table.

  • Create and delete (7) view only affects the view itself, does not affect the basic table corresponds.

Contact between the two:

  • View (view) is created on the basic table the table, its structure (i.e., a column defined) and the content (i.e., all records) are from the base table, it is based on the presence of a base table exists. A view may correspond to a base table, and

  • You may correspond to a plurality of base tables. View abstract and establish new relationships in the logical sense basic table.

29, to pay special attention when using triggers.

When using the trigger should be noted that, for the same table, the same event can only create a trigger, such as a table account creates a BEFORE INSERT trigger, if you create a BEFORE INSERT trigger on the table again account, MySQL will be given at this time, you can only create BEFORE UPDATE or AFTER INSERT trigger on the table type of account. Flexible use will trigger operation to save a lot of trouble. Click here summarize the 55 MYSQL to face questions BAT interview.

30, promptly remove the trigger no longer needed.

After the trigger definition, each time the trigger event, the trigger will activate the trigger and execute the statements. If demand changes, but trigger does not make the appropriate changes or deleted, the trigger will still perform the old statement, which will affect the integrity of the new data. So, to no longer use triggers promptly deleted.

31, which method should be used to create a user?

There are several ways to create a user: GRANT statement, CREATE USER statement and direct manipulation user table. Generally, it is best to use GRANT or CREATE USER statement, rather than directly to the user information into user table, because the user table stores the global level of authority as well as other account information, if the user accidentally destroyed the records in the table, it may be MySQL server will have a great impact.

32, mysqldump backup file can only be used in MySQL do?

Mysqldump text file is actually a backup copy of the database, not only can use this file to restore the database in MySQL, but also through simple changes to the document, you can use the file to restore the database in SQL Server or Sybase and other databases. This is achieved in a way migration between databases.

33, how to select a backup tool?

Directly copy the data file is the most direct, fast backup method, but the disadvantage is basically incremental backups can not be achieved. You must be sure not to use these tables when backup. If the server is replicated to modify it in a table at the same time, the copy is not valid. When the backup file, best to turn off the server, then restart the server. In order to ensure data consistency, you need to before the backup file, execute the following SQL statement:

CREATE PROCEDURE useInfo(IN u_name VARCHAR(50) character set gbk, OUT u_age INT)

Next to the directory. mysqlhotcopy is a PERL program that uses LOCK TABLES, FLUSH TABLES and cp or scp to quickly back up the database. It is the fastest way to back up the database or single tables, but it can only run on the machine where the database file, and mysqlhotcopy only be used for backup MyISAM tables.

mysqlhotcopy suitable for small database backup, the amount of data, you can use mysqlhotcopy program to conduct a full backup every day. mysqldump guide to the data table SQL script file, relatively appropriate upgrades between different versions of MySQL, which is the most commonly used backup method. mysqldump will be slower than direct copying. That is, the data in memory is flushed to disk, and lock the data table, to ensure that the replication process there will be no new data is written. This approach backed up data recovery is also very simple, direct copy back to the original database

34, which usually logs should be opened?

Log only affect the performance of MySQL, it will take up a lot of disk space. Therefore, if necessary, should be as little as possible to open the log. According to different environment, different log can be considered open. For example, to optimize the development environment of low query efficiency statement, you can turn on slow query log; if you need to record all query operations the user can turn on general query log; If you need to record change data, you can open the binary logs; error log is the default open.

35, how to use the binary log?

The binary log is mainly used to record data changes. If you need to record changes in the database, you can open the binary log. Based on the characteristics of binary log, not only can be used for data recovery, it can be used for data replication.

In the case of regular backups of the database, if data loss, you can recover most of the data backup, and then use the binary log to restore data changes after the most recent backup. In the hot standby situation, you can use the change log MySQL binary data, and then copy the changed portion to the backup server.

36, how to use the slow query log?

Slow query log is mainly used to record a long time query log. In the development environment, you can turn on slow query log to record a longer query time query, and then optimize these statements. By value long_query_time with the flexibility to master the different degrees of slow queries.

37, is not indexing the better?

Reasonable index can improve query speed, but not index the better. In performing insert statement, MySQL to index the newly inserted record. So too many indexes can cause slow insertion. In principle, the query is only used in the field before indexing.

Guess you like

Origin www.cnblogs.com/liuye007/p/11112771.html